你实际上并没有阻止主线程的进程:
“正确的”(*)方法是通过连接所有线程来确保完成所有线程:def main() :
# keep reference to threads
threads = [threading.Thread(target=run) for _ in range(20)]
# start all threads
for t in threads:
t.start()
#20 jobs are put in the queue
for x in range(1,21) :
q.put(x)
#waits until queue is empty and then continues
q.join()
# join all threads
for t in threads:
t.join()
*但是,由于线程处于无限循环中,即使任务已完成,也无法正常工作。在
因此,另一种方法是确保您在报告任务之前等待:
^{pr2}$
不过,线程仍然被阻塞。你所要做的就是给线程一个消息,告诉他们退出。比如:def run() :
while True :
task = q.get()
if task == 'stop':
break
# simulate processing time *before* actual reporting
time.sleep(2)
print('Just finished task number',task)
q.task_done()
现在只需告诉主线程为所有线程放置足够的停止消息,以最终退出其无限循环:def main() :
# keep reference to threads
threads = [threading.Thread(target=run) for _ in range(20)]
# start all threads
for t in threads:
t.start()
#20 jobs are put in the queue
for x in range(1,21):
q.put(x)
for x in range(20):
# stop all threads after tasks are done
q.put('stop')
# waits until queue is empty and then continues
q.join()
# join all threads
for t in threads:
t.join()
提示:您不应该使用“幻数”,例如20。在模块级别有一个名为THREADS_COUNT的全局变量,因此当您想测试不同的配置时,只需更改一个位置。在