【发布时间】:2018-03-01 13:33:28
【问题描述】:
我有这个代码:
class ExtendedProcess(multiprocessing.Process):
def __init__(self):
super(ExtendedProcess, self).__init__()
self.stop_request = multiprocessing.Event()
def join(self, timeout=None):
logging.debug("stop request received")
self.stop_request.set()
super(ExtendedProcess, self).join(timeout)
def run(self):
logging.debug("process has started")
while not self.stop_request.is_set():
print "doing something"
logging.debug("proc is stopping")
当我在进程上调用 start() 时,它应该永远运行,因为 self.stop_request() 没有设置。几毫秒后,join() 被自己调用并中断运行。到底是怎么回事!?为什么join是自己调用的?
此外,当我启动调试器并逐行运行时,它突然工作正常......我错过了什么?
好的,感谢 ely 的回答让我想到了原因:
存在竞争条件 -
- 新进程已创建...
- 当它自己启动并即将运行 logging.debug("process has started") 时,主函数会结束。
- main 函数调用 sys exit 和 on sys exit python 调用所有已完成的进程以使用 join() 关闭。
- 因为进程实际上并没有点击“while not self.stop_request.is_set()”,所以调用了连接并调用了“self.stop_request.set()”。现在 stop_request.is_set 和代码关闭。
【问题讨论】:
标签: python python-2.7 python-multiprocessing