小编SMX*_*SMX的帖子

什么时候需要 Queue.join() ?

Python 3 文档给出了使用队列的工作线程的示例(https://docs.python.org/3/library/queue.html):

def worker():
    while True:
        item = q.get()
        if item is None:
            break
        do_work(item)
        q.task_done()

q = queue.Queue()
threads = []
for i in range(num_worker_threads):
    t = threading.Thread(target=worker)
    t.start()
    threads.append(t)

for item in source():
    q.put(item)

# block until all tasks are done
q.join()

# stop workers
for i in range(num_worker_threads):
    q.put(None)
for t in threads:
    t.join()
Run Code Online (Sandbox Code Playgroud)

在这个例子中,为什么是q.join()必要的?q.put(None)后续的和操作难道不会t.join()完成同样的事情,即阻塞主线程直到工作线程完成吗?

python queue multithreading python-3.x

4
推荐指数
1
解决办法
5189
查看次数

标签 统计

multithreading ×1

python ×1

python-3.x ×1

queue ×1