我不明白为什么下面的代码块。我尝试简单地循环一段时间,然后发送一条消息到线程停止。我的进程类如下。在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()时,我的线程没有跳出它的循环?在