python 多进程成员变量未设置

1 投票
1 回答
577 浏览
提问于 2025-04-15 21:53

在下面的脚本中,我得到了“收到停止消息”的输出,但这个过程却从来没有结束。为什么会这样呢?除了终止或者使用os.kill,还有其他方法可以结束一个进程吗?

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()

1 个回答

3

这个 start 方法把对象复制到了一个单独的进程里,然后在那个进程中执行 run 方法。而 end 方法就没什么特别的,它是在调用它的那个进程中运行的——它对对象所做的修改不会影响到复制出来的那个对象。

所以,建议使用合适的进程间通信方式,比如一个 multiprocessing.Event 实例,例如:

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()

如你所见,所需的修改非常少。

撰写回答