← Back to Python, page 5

python-0093 · Hard senior

Build a thread-safe producer and consumer pipeline with queue.Queue and clean shutdown.

queue.Queue is thread-safe and handles locking internally: producers put items, consumers get them, and task_done with join tracks completion. A bounded queue applies back-pressure so producers cannot outrun consumers. Shut down by sending one sentinel per consumer, or with Queue.shutdown in Python 3.13.

Full answer
python
import queue, threading

def producer(q, n):
    for i in range(n):
        q.put(i)

def consumer(q, results, lock):
    while True:
        try:
            item = q.get()
        except queue.ShutDown:
            return
        with lock:
            results.append(item * item)
        q.task_done()

q = queue.Queue(maxsize=5)
results, lock = [], threading.Lock()
workers = [threading.Thread(target=consumer, args=(q, results, lock)) for _ in range(3)]
for w in workers: w.start()
producer(q, 20)
q.join()
q.shutdown()
for w in workers: w.join()
print(len(results), sum(results), sorted(results)[:5])
print(all(not w.is_alive() for w in workers))

Output:

text
20 2470 [0, 1, 4, 9, 16]
True

Three consumers process twenty items; maxsize=5 blocks the producer whenever the queue is full. q.join() waits until every item has been marked done, then q.shutdown() (new in 3.13) makes blocked get calls raise queue.ShutDown, so the consumers exit and the threads can be joined. On older versions, put one sentinel such as None per consumer. The results list is sorted before printing because consumers finish in an unpredictable order; the sum, 2470, is deterministic. The lock around append is technically unnecessary for a single list append in CPython, but it makes the intent explicit and stays correct with free-threaded builds.

python
import queue, threading

def producer(q, n):
    for i in range(n):
        q.put(i)

def consumer(q, results, lock):
    while True:
        try:
            item = q.get()
        except queue.ShutDown:
            return
        with lock:
            results.append(item * item)
        q.task_done()

q = queue.Queue(maxsize=5)
results, lock = [], threading.Lock()
workers = [threading.Thread(target=consumer, args=(q, results, lock)) for _ in range(3)]
for w in workers: w.start()
producer(q, 20)
q.join()
q.shutdown()
for w in workers: w.join()
print(len(results), sum(results), sorted(results)[:5])
print(all(not w.is_alive() for w in workers))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • queue.Queue handles locking
  • Bounded queues give back-pressure
  • task_done and join track completion
  • Queue.shutdown in 3.13, sentinels before
  • Results arrive in nondeterministic order

Common mistakes

  • Unbounded queues that grow without limit
  • Consumers that never exit, so join hangs

Follow-ups

  • How would you propagate an exception from a consumer?
  • When would multiprocessing.Queue be needed?

Tips

  • Explain shutdown