Sub topic 11
Thread-safe queues with queue.Queue
This chapter assumes you know basic Python threads (threading.Thread), the FIFO queue operations from earlier chapters, and how collections.deque works. By the end you should be able to build a producer-consumer pipeline with queue.Queue and explain when to use it instead of a deque.
Why a plain deque is not enough
A deque makes append and popleft atomic in CPython, so single operations will not corrupt it. That is not enough for coordination between threads. Two problems remain:
- A consumer that finds the deque empty must busy-wait, which wastes CPU, or sleep, which adds latency.
- A check-then-act sequence such as
if d: d.popleft()is not atomic. Another thread can empty the deque between the check and the pop, and you get anIndexError.
queue.Queue solves both. It is a FIFO queue with internal locking and condition variables. Threads can block while waiting for items or for free space.
The core operations
| Method | Behavior |
|---|---|
| `put(item)` | Adds an item. Blocks while the queue is full. |
| `get()` | Removes and returns the oldest item. Blocks while the queue is empty. |
| `put_nowait(item)` | Raises `queue.Full` instead of blocking. |
| `get_nowait()` | Raises `queue.Empty` instead of blocking. |
| `task_done()` | Called by a consumer after it finishes one item. |
| `join()` | Blocks until every item put in the queue has been marked done. |
| `qsize()` | Approximate size. Other threads may change it immediately. |
put and get also accept timeout=seconds. If the wait runs out, they raise queue.Full or queue.Empty.
A maxsize of 0 or less (the default) means the queue is unbounded. A positive maxsize makes it bounded, and put blocks when it is reached.
A producer-consumer example
import queue
import threading
q = queue.Queue(maxsize=2)
def worker():
while True:
item = q.get()
if item is None:
q.task_done()
break
print("processed", item)
q.task_done()
t = threading.Thread(target=worker)
t.start()
for i in range(5):
q.put(i) # blocks when the queue already holds 2 items
q.put(None) # sentinel that tells the worker to stop
q.join() # waits until every item has been marked done
t.join()The main thread is the producer and the worker thread is the consumer. Because maxsize=2, the producer pauses whenever the worker falls behind. This is called backpressure. It keeps memory use bounded when producers are faster than consumers.
The None value is a sentinel, a special item that means "no more work". Each consumer must receive one sentinel, so with three workers you put three sentinels.
How task_done and join work
The queue keeps a counter of unfinished tasks. Each put increments it. Each task_done decrements it. join blocks until the counter reaches zero.
Note that get does not decrement the counter. Only task_done does. This lets join wait for the work to finish, not merely for the items to be removed from the queue.
Common errors
- Forgetting
task_done.join()then waits forever. - Calling
task_donetoo many times. This raisesValueError, because the counter would go below zero. - Skipping
task_donewhen processing fails. Put the call in afinallyblock so an exception does not hangjoin(). - Trusting
qsize(),empty(), orfull()for decisions. Their answers can be stale by the time you act on them. Useget_nowait()and catchqueue.Empty. - Forgetting the sentinel. A non-daemon worker blocked in
get()keeps the program from exiting.
import queue
q = queue.Queue()
def handle(item):
return item * 2
q.put(21)
try:
item = q.get(timeout=1)
try:
print(handle(item))
finally:
q.task_done()
except queue.Empty:
print("no work arrived in time")queue.Queue versus collections.deque
| Need | Choose |
|---|---|
| Threads that wait for work or for space | `queue.Queue` |
| Backpressure through `maxsize` | `queue.Queue` |
| Tracking completion with `join` | `queue.Queue` |
| Fast single-threaded queue, BFS, sliding window | `collections.deque` |
| Access at both ends, `rotate`, or `maxlen` | `collections.deque` |
queue.Queue is slower than deque because each call acquires locks. Use it where you need its coordination features, and use deque elsewhere. It also uses a deque internally for storage.
Related classes in the same module are queue.LifoQueue (a stack) and queue.PriorityQueue, which the next chapter covers. queue.Queue is for threads. For separate processes, use multiprocessing.Queue. For asyncio code, use asyncio.Queue.
Exercise
A worker loop calls q.get(), processes the item, and calls q.task_done() only when processing succeeds. One item raises an exception, and the main thread's q.join() never returns. Why, and how do you fix it?
Show answer
The unfinished-task counter is decremented only by task_done(). The failing item never decrements it, so join() waits forever. Fix it by calling task_done() in a finally block around the processing code, so it runs whether or not the processing raises an exception.
Exercise
Why is if not q.empty(): item = q.get() unreliable with several consumer threads, and what should you write instead?
Show answer
Another consumer can take the last item between the empty() check and the get(), so get() blocks forever or the check gives a wrong answer. Call q.get_nowait() inside a try block and catch queue.Empty, or use q.get(timeout=...).