Python threads and queue example(Python 线程和队列示例)
问题描述
我是 python 新手(我来自 PHP),我一直在阅读教程并尝试了几天,但我无法理解这个队列示例(http://docs.python.org/2/library/queue.html)
I'm new to python (I come from PHP), I've been reading tutorials and trying things for a couple of days but I can't understand this queue example (http://docs.python.org/2/library/queue.html)
def worker():
while True:
item = q.get()
do_work(item)
q.task_done()
q = Queue()
for i in range(num_worker_threads):
t = Thread(target=worker)
t.daemon = True
t.start()
for item in source():
q.put(item)
q.join() # block until all tasks are done
我不明白的是工作线程是如何完成和存在的.我已经阅读了 q.get() 阻塞,直到一个项目可用,所以如果所有项目都已处理并且队列中没有任何项目,为什么 q.get() 不会永远阻塞?
The thing I don't understand is how the worker thread completes and exists. I've read q.get() blocks until an item is available, so if all items are processed and none is left in the queue why q.get() doesn't block forever?
推荐答案
这段代码中线程没有正常退出(确实是队列为空时阻塞).程序不会等待它们,因为它们是 守护线程.
Threads do not exit normally in this code (they are indeed blocked when the queue is empty). The program doesn't wait for them because they're daemon threads.
程序不会立即退出,也不会因为 q.join
和 q.task_done
调用.
The program doesn't exit immediately and doesn't block forever because of q.join
and q.task_done
calls.
每当将项目添加到队列中时,未完成任务的计数就会增加.每当消费者线程调用 task_done()
以指示该项目已被检索并且所有工作都已完成时,计数就会下降.当未完成任务的计数降至零时,join()
解除阻塞,程序无需等待守护线程即可存在.
The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done()
to indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join()
unblocks, and the program exists without waiting for daemon threads.
这篇关于Python 线程和队列示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python 线程和队列示例
基础教程推荐
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01