Producer-Consumer Pattern Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn your Concurrency question into a ready to paste AI prompt, free →
Key Takeaways
- ✓Producer-Consumer Pattern runs in O(1) per op time and O(n) space, in Python as in every other language.
- ✓queue.Queue(maxsize=n) is the thread-safe bounded queue, with put and get blocking by default, plus task_done and join for completion tracking.
- ✓Always pass maxsize. Use a sentinel value (a module-level object() or None) pushed once per consumer to signal shutdown, and have each consumer re-raise or exit on receiving it.
- ✓The Python trap: The default queue.Queue() is UNBOUNDED, so the safe-looking constructor is the dangerous one.
- ✓Each put/get pair costs on the order of a microsecond because it acquires a lock and touches a condition variable through the interpreter, perfectly fine at thousands of items per second, wasteful at millions.
What Producer-Consumer Pattern actually is
Producer-Consumer Pattern in Python: what you actually reach for
Python implementation
import queue
import threading
SENTINEL = object()
def consumer(q: queue.Queue) -> None:
while True:
item = q.get()
try:
if item is SENTINEL:
return
handle(item)
finally:
q.task_done() # in finally, or q.join() hangs on any exception
def handle(item: object) -> None: ...
# BOUNDED. queue.Queue() with no maxsize is unbounded and will grow
# until the process dies if producers outpace consumers.
q: queue.Queue = queue.Queue(maxsize=1000)
workers = [threading.Thread(target=consumer, args=(q,), daemon=True) for _ in range(4)]
for w in workers:
w.start()
for item in range(10_000):
q.put(item) # BLOCKS at 1000, that is the backpressure
for _ in workers:
q.put(SENTINEL) # one sentinel per consumer
for w in workers:
w.join()Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(1) per op
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Producer-Consumer Pattern?
queue.Queue(maxsize=n) is the thread-safe bounded queue, with put and get blocking by default, plus task_done and join for completion tracking. asyncio.Queue is the identical API for coroutines on one thread, and multiprocessing.Queue crosses process boundaries by pickling. concurrent.futures.ThreadPoolExecutor already contains a producer-consumer queue, so if your consumers are uniform workers, submit to an executor rather than building the queue by hand.
What is the most common Python mistake when implementing Producer-Consumer Pattern?
The default queue.Queue() is UNBOUNDED, so the safe-looking constructor is the dangerous one. The second trap is specific to CPython: the GIL means threaded producers and consumers doing CPU work do not run in parallel at all, so a thread-based pipeline that looks concurrent delivers no speedup on compute and only helps when the work releases the GIL (I/O, or C extensions like NumPy), use ProcessPoolExecutor for CPU-bound stages. Third, q.join() blocks forever if any consumer raises before calling task_done.
How does Producer-Consumer Pattern actually perform in Python?
Each put/get pair costs on the order of a microsecond because it acquires a lock and touches a condition variable through the interpreter, perfectly fine at thousands of items per second, wasteful at millions. Batch small items into lists and enqueue the batch when throughput matters; the queue overhead then amortises over the batch. asyncio.Queue is cheaper than queue.Queue because it needs no OS-level locking, just event-loop scheduling. Time complexity is O(1) per op and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialMost AI and dev tools have a student plan. See which ones and how to claim them on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.