On Unix, subprocesses are spawned using os.fork
. The fork copies globals (or uses copy-on-write) so each process (the parent and the child) have their own copy of the globals. On Windows, a second Python process is spawned and the calling module is imported.
In either case (on Unix or Windows) when the parent modifies a global variable, the child's global variable of the same name does not change. Thus calling parser_thread.stop()
in the main process does not affect the value of self.scp_done
in the subprocess.
multiprocessing
does provide certain objects which can facilitate sharing state between processes, such as mp.Value
. For a simple boolean value, you could also use an mp.Event:
import multiprocessing as mp
import time
class LogParserProcess(mp.Process):
def __init__(self):
super(LogParserProcess, self).__init__()
self.done = mp.Event()
self.flights_to_add = ()
def stop(self):
self.done.set()
print 'Stopping: ' + str(self.done.is_set())
def run(self):
file_list = ()
while not self.done.is_set() or len(file_list) > 0:
print 'Status ' + str(self.done.is_set()) + ' ' + str(len(file_list))
files_to_copy = "file1 file2 file3"
proc = LogParserProcess()
proc.start()
print 'BEFORE COPY ' + str(proc.done.is_set())
time.sleep(1)
print 'AFTER COPY ' + str(proc.done.is_set())
proc.stop()
print 'AFTER STOP ' + str(proc.done.is_set())
proc.join()
print 'AFTER JOIN ' + str(proc.done.is_set())
prints
BEFORE COPY False
Status False 0
...
Status False 0
AFTER COPY False
Status False 0
Status False 0
Status False 0
Stopping: True
AFTER STOP True
AFTER JOIN True