In the following script, I get the “stop message received” output but the process never ends. Why is that? Is there another way to end a process besides terminate or os.kill that is along these lines?
from multiprocessing import Process
from time import sleep
class Test(Process):
def __init__(self):
Process.__init__(self)
self.stop = False
def run(self):
while self.stop == False:
print "running"
sleep(1.0)
def end(self):
print "stop message received"
self.stop = True
if __name__ == "__main__":
test = Test()
test.start()
sleep(1.0)
test.end()
test.join()
The
startmethod has cloned the object into a separate process, where it executesrun. Theendmethod is nothing special, so it runs in the process that calls it — the changes it performs to that object are not sent to the clone object.So, use instead an appropriate means of interprocess communication, such as a multiprocessing.Event instance, e.g.:
As you see, the required changes are minimal.