Concurrency and Modules
Queue Worker
A Queue hands work from one thread to another. The source stays in one pane,
and replay uses thread colors to show producer and consumer events.
Producer and Consumer
queue_worker.py
import queue
import threading
work = queue.Queue()
def producer(count):
for number in range(1, count + 1):
item = "job-" + str(number)
work.put(item)
print("queued=" + item)
work.put("done")
def consumer():
while True:
item = work.get()
if item == "done":
print("stopped")
break
print("handled=" + item)
count =
producer_thread = threading.Thread(target=producer, args=(count,))
consumer_thread = threading.Thread(target=consumer)
producer_thread.start()
consumer_thread.start()
producer_thread.join()
consumer_thread.join()
import queue
import threading
work = queue.Queue()
def producer(count):
for number in range(1, count + 1):
item = "job-" + str(number)
work.put(item)
print("queued=" + item)
work.put("done")
def consumer():
while True:
item = work.get()
if item == "done":
print("stopped")
break
print("handled=" + item)
count =
producer_thread = threading.Thread(target=producer, args=(count,))
consumer_thread = threading.Thread(target=consumer)
producer_thread.start()
consumer_thread.start()
producer_thread.join()
consumer_thread.join()
queue handoff
`put()` adds work, and `get()` removes it. A small sentinel value can tell the consumer that no more work is coming.