Kaydet (Commit) de311345 authored tarafından Victor Stinner's avatar Victor Stinner

Issue #12155: Fix queue doc example to join threads

Use None as a sentinel to stop a worker.
üst 926ce700
...@@ -158,22 +158,32 @@ fully processed by daemon consumer threads. ...@@ -158,22 +158,32 @@ fully processed by daemon consumer threads.
Example of how to wait for enqueued tasks to be completed:: Example of how to wait for enqueued tasks to be completed::
def worker(): def worker():
while True: while True:
item = q.get() item = q.get()
do_work(item) if item is None:
q.task_done() break
do_work(item)
q = Queue() q.task_done()
for i in range(num_worker_threads):
t = Thread(target=worker) q = queue.Queue()
t.daemon = True threads = []
for i in range(num_worker_threads):
t = threading.Thread(target=worker)
t.start() t.start()
threads.append(t)
for item in source(): for item in source():
q.put(item) q.put(item)
q.join() # block until all tasks are done # 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()
.. seealso:: .. seealso::
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment