我不明白为什么下面的代码块。我尝试简单地循环一段时间,然后发送一条消息到线程停止。我的进程类如下。在class Worker(multiprocessing.Process):
def __init__(self, queue):
multiprocessing.Process.__init__(self)
self.queue = queue
self.running = True
def run(self):
print 'entered run'
while self.running:
print 'thread time:', time.time()
time.sleep(.6)
print 'thread end'
return 0
很直接。我的主要是这样的:
^{pr2}$
所以,我希望这个程序启动一个进程,它将沿着main的边运行它自己的循环。当这发生时,Main()将休眠3秒,然后将worker进程中的循环条件设置为False,这样它就可以脱离循环。然后他们都会打印一条很好的“完成”消息,程序就退出了。但是,问题是main线程在进程有机会显示其消息之前退出。在
例如,输出如下所示:>> entered run
>> thread time: 1358444245.31
>> thread time: 1358444245.91
>> thread time: 1358444246.51
>> thread time: 1358444247.11
>> thread time: 1358444247.71
>> Main end
所以,稍微读一下,我就会发现join()被用来阻塞,直到一个线程完成执行。接下来,我在中断线程中的循环条件后立即添加一个join()调用。我的想法是,这将阻止main,直到进程有时间关闭自己。在if __name__ == '__main__':
queue = Queue()
p = Worker(queue)
p.daemon = True
p.start()
time.sleep(3)
p.running = False
p.join() ##
print 'Main end'
然而,这表现得出人意料。一旦我添加了那一行,线程就永远不会停止执行,因此main会无限期地阻塞。下面的输出将旋转到永恒。在>> entered run
>> thread time: 1358444362.44
>> thread time: 1358444363.04
>> thread time: 1358444363.64
>> thread time: 1358444364.24
>> thread time: 1358444364.84
>> thread time: 1358444365.44
>> thread time: 1358444366.04
>> thread time: 1358444366.64
>> thread time: 1358444367.24
>> thread time: 1358444367.84
>> thread time: 1358444368.44
>> thread time: 1358444369.04
>> thread time: 1358444369.64
>> thread time: 1358444370.24
这是怎么回事?为什么当我添加join()时,我的线程没有跳出它的循环?在
本文发布于:2024-01-30 02:25:58,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170655276218577.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |