views:

79

answers:

1

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()
+2  A: 

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.Evet 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.

Alex Martelli