Thread Communication (Queue)
Why Queue?
queue.Queuequeue.Queue is thread-safe.
Use it to:
- pass tasks from producer threads to worker threads
- avoid manual lock management
Producer-consumer example
queue_example.py
import threading
import queue
import time
q = queue.Queue()
def producer():
for i in range(5):
q.put(i)
print("produced", i)
q.put(None) # sentinel
def consumer():
while True:
item = q.get()
try:
if item is None:
break
print("consuming", item)
time.sleep(0.2)
finally:
q.task_done()
t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer)
t1.start(); t2.start()
t1.join()
q.join() # wait until all tasks are marked done
print("All tasks processed")queue_example.py
import threading
import queue
import time
q = queue.Queue()
def producer():
for i in range(5):
q.put(i)
print("produced", i)
q.put(None) # sentinel
def consumer():
while True:
item = q.get()
try:
if item is None:
break
print("consuming", item)
time.sleep(0.2)
finally:
q.task_done()
t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer)
t1.start(); t2.start()
t1.join()
q.join() # wait until all tasks are marked done
print("All tasks processed")Tips
- Use a sentinel (
NoneNone) to stop consumers. - Always call
task_done()task_done()(often in afinallyfinally).
๐งช Try It Yourself
Exercise 1 โ Put and Get
Exercise 2 โ Producer-Consumer
Exercise 3 โ Queue Size
If this helped you, consider buying me a coffee โ
Buy me a coffeeWas this page helpful?
Let us know how we did
