Sub topic 12
Building pipelines with asyncio.Queue
This chapter assumes you can write coroutines, start tasks with asyncio.create_task, and use Semaphore to limit concurrency. You should also know what a context switch at await means.
Why a queue
A producer-consumer pipeline splits work into stages. One stage creates items and another processes them. asyncio.Queue connects the stages. It is a first-in, first-out buffer whose put and get methods are coroutines, so a task waits at the queue without blocking the event loop.
A queue gives you two things that gather over a list does not:
- Stages run at the same time. Consumers start work as soon as the first item arrives.
- A bounded queue applies backpressure. When the buffer is full,
await q.put(...)suspends the producer until a consumer takes an item. Memory use stays flat even if the producer is much faster.
A minimal pipeline
import asyncio
async def producer(q):
for i in range(5):
await q.put(i)
async def consumer(q):
while True:
item = await q.get()
print("got", item)
q.task_done()
async def main():
q = asyncio.Queue(maxsize=2)
consumer_task = asyncio.create_task(consumer(q))
await producer(q)
await q.join()
consumer_task.cancel()
asyncio.run(main())Here is how it works:
Queue(maxsize=2)holds at most two items. Withmaxsize=0(the default) the queue is unbounded and never applies backpressure.- The consumer is a task that loops forever, so it starts running as soon as
mainfirst suspends. - The producer's third
putsuspends until the consumer has taken an item. q.join()waits untiltask_done()has been called once for every item that was put.- The consumer is idle, waiting in
get(), somaincancels it.
Counting with task_done
join() does not look at the queue size. It looks at an internal counter of unfinished tasks. put raises the counter and task_done lowers it. If you forget task_done, join() waits forever. If you call it more times than you put items, ValueError is raised.
Call task_done in a finally block when processing can fail, so one bad item does not hang the pipeline.
Several consumers
Adding consumers is a matter of starting more tasks on the same queue. Each item goes to exactly one consumer.
import asyncio
async def consumer(name, q):
while True:
item = await q.get()
try:
await asyncio.sleep(0.1)
print(name, "handled", item)
finally:
q.task_done()
async def main():
q = asyncio.Queue(maxsize=4)
workers = [asyncio.create_task(consumer(f"w{i}", q)) for i in range(3)]
for item in range(8):
await q.put(item)
await q.join()
for w in workers:
w.cancel()
await asyncio.gather(*workers, return_exceptions=True)
asyncio.run(main())The last gather with return_exceptions=True waits for the cancelled workers to finish, so none are left pending when the program exits.
Common mistakes
- Using
q.get_nowait()orq.put_nowait()in a loop. They raiseQueueEmptyorQueueFullinstead of waiting. - Forgetting to stop the consumers. An infinite
while Trueconsumer must be cancelled, or told to stop with a sentinel value such asNone. - Using
queue.Queuefrom the standard library in async code. Itsgetblocks the whole event loop.
Exercise
A pipeline calls await q.join() and never finishes, even though the producer has put all its items and the queue is empty. What is the most likely cause?
Show answer
The consumers took the items but did not call q.task_done() for each one, for example because an exception skipped it. join() waits on the unfinished-tasks counter, not on the queue size. Call task_done() in a finally block.