Reputation: 2655
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()
Upvotes: 1
Views: 585
Reputation: 882641
The start
method has cloned the object into a separate process, where it executes run
. The end
method 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.:
from multiprocessing import Process, Event
from time import sleep
class Test(Process):
def __init__(self):
Process.__init__(self)
self.stop = Event()
def run(self):
while not self.stop.is_set():
print "running"
sleep(1.0)
def end(self):
print "stop message received"
self.stop.set()
if __name__ == "__main__":
test = Test()
test.start()
sleep(1.0)
test.end()
test.join()
As you see, the required changes are minimal.
Upvotes: 3