bpo-40387: Improve queue join() example. (GH-19724)
This commit is contained in:
parent
68b352a698
commit
88499f15f5
|
@ -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
|
||||||
|
|
Loading…
Reference in New Issue