gpt4 book ai didi

Python - Queue 究竟是如何工作的?

转载 作者:太空宇宙 更新时间:2023-11-03 14:44:07 24 4
gpt4 key购买 nike

关于文档中的示例: https://docs.python.org/2/library/queue.html#Queue.Queue.get

def worker():
while True:
item = q.get()
do_work(item)
q.task_done()

工作人员实际上如何知道所有工作都已完成,队列为空并且我们可以退出?没看懂。。。

最佳答案

您的 worker 在 while True: 循环中挂起,这意味着函数/线程将永远不会返回。

“魔法”在于您未显示的代码:

 t = Thread(target=worker)
t.daemon = True
t.start()

daemon参数控制上层线程何时可以退出

The entire Python program exits when no alive non-daemon threads are left.

这意味着,程序将退出,因为主线程存在。工作线程会继续存在,但会在主线程结束时被销毁(因为“没有非守护线程留下”)。

主线程退出条件为

q.join()

join 的文档将在停止阻止执行时显示。

[...] When the count of unfinished tasks drops to zero, join() unblocks.

关于Python - Queue 究竟是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51134971/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com