Python线程和队列示例 [英] Python threads and queue example

查看:54
本文介绍了Python线程和队列示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手(我来自PHP),我已经阅读教程并尝试了几天,但我无法理解该队列示例(

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.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线程和队列示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆