bpo-40387: Improve queue join() example. (GH-19724)

This commit is contained in:
Raymond Hettinger 2020-04-26 18:11:27 -07:00 committed by GitHub
parent 68b352a698
commit 88499f15f5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 12 additions and 16 deletions

View File

@ -190,32 +190,28 @@ 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::
import threading, queue
q = queue.Queue()
def worker(): def worker():
while True: while True:
item = q.get() item = q.get()
if item is None: print(f'Working on {item}')
break print(f'Finished {item}')
do_work(item)
q.task_done() q.task_done()
q = queue.Queue() # turn-on the worker thread
threads = [] threading.Thread(target=worker, daemon=True).start()
for i in range(num_worker_threads):
t = threading.Thread(target=worker)
t.start()
threads.append(t)
for item in source(): # send thirty task requests to the worker
for item in range(30):
q.put(item) q.put(item)
print('All task requests sent\n', end='')
# block until all tasks are done # block until all tasks are done
q.join() q.join()
print('All work completed')
# stop workers
for i in range(num_worker_threads):
q.put(None)
for t in threads:
t.join()
SimpleQueue Objects SimpleQueue Objects