Queues between tasks: producers and consumers
🌍 In real life. In a busy restaurant, waiters clip order slips onto a rail, and the cooks take the next slip whenever they are free. A waiter doesn't stand by the stove waiting for one cook, and a cook doesn't chase waiters. They only wait in two cases: a cook waits when the rail is empty, and a waiter waits when the rail is full.
When several asyncio tasks pass work to each other, asyncio.Queue is that rail.
The idea in one sentence: an asyncio.Queue lets producer tasks hand items to consumer tasks: put adds an item, await get() takes the oldest one and waits while the queue is empty, and task_done() with await join() tells you when every item has been handled.
Its words:
- producer: a task that makes work and puts it in the queue (the waiter)
- consumer: a task that takes work out and does it (the cook)
asyncio.Queue(maxsize=n): first in, first out; with amaxsize,await put(...)waits while the queue is fullqueue.task_done(): "I've finished the item I took";await queue.join()waits until every item put in has been marked done- backpressure: a full queue slowing the producers down to the consumers' speed
Step by step, two cooks and three orders:
- Three slips go on the rail: tea, toast, egg.
- Ana takes tea and Bo takes toast; both cook at the same time.
- Ana finishes first, marks tea done, and takes egg.
- Bo finishes toast and waits: the rail is empty.
- Ana finishes egg. Three items in, three marked done, so
join()returns.
A rail that fills up. With maxsize, a fast producer can't pile up thousands of slips: await put(...) waits until a consumer takes one. To tell a consumer there is no more work, a common habit is to put a special sentinel value, like None, at the end.
import asyncio
async def waiter(orders):
for dish in ["tea", "toast", "egg", "rice"]:
await orders.put(dish)
print("ordered", dish, "| on the rail:", orders.qsize())
await orders.put(None) # no more orders
async def cook(orders):
while (dish := await orders.get()) is not None:
await asyncio.sleep(0.05)
print(" cooked", dish)
async def main():
orders = asyncio.Queue(maxsize=2) # the rail holds 2 slips
await asyncio.gather(waiter(orders), cook(orders))
asyncio.run(main())Why a queue and not a list? A list can't make a task wait. With a list, a consumer must keep checking "anything yet?" in a loop, wasting time, and a producer has no way to slow down. A queue does both waits for you, in the right order. Each put and get is O(1): inside, it is a deque (Chapter 40).
Mistakes and edge cases.
- Forgetting task_done().
join()waits until every item is marked done, so one missingtask_done()makes it wait for ever. (Here, press Stop.) - Forgetting await.
dish = orders.get()gives a coroutine object, not an item. Writedish = await orders.get(). - One sentinel for several consumers. Each consumer stops at the
Noneit takes, so two consumers need twoNones; with one, the second waits for ever. - The _nowait versions don't wait.
put_nowaiton a full queue raisesasyncio.QueueFull, andget_nowaiton an empty one raisesasyncio.QueueEmpty. - Consumers that never stop. A
while Trueconsumer runs until it is cancelled. Cancel it, or send a sentinel.
Quiz
The queue is empty. What does await orders.get() do?
- Pauses this task until something is put in
- Returns None at once
- Raises an error
asyncio.Queue(maxsize=2) already holds 2 items. What does await orders.put(x) do?
- Waits until a consumer takes an item
- Raises QueueFull
- Throws away the oldest item
What does this print?
import asyncio async def main(): q = asyncio.Queue() for x in [3, 1, 2]: q.put_nowait(x) print(q.qsize(), await q.get(), await q.get()) asyncio.run(main())With two cooks this never finishes: one cook stops, the other waits for ever. Which line is wrong?
import asyncio async def cook(name, orders): while (dish := await orders.get()) is not None: print(name, "made", dish) async def main(): orders = asyncio.Queue() for dish in ["tea", "egg", None]: orders.put_nowait(dish) await asyncio.gather(cook("Ana", orders), cook("Bo", orders)) asyncio.run(main())What are task_done() and join() for?
- join() waits until every item put in has been marked finished with task_done()
- task_done() empties the queue, and join() joins two queues
- They stop the consumer tasks
Coding tasks
Write the consumer
cook(orders): take dishes from the queue until it getsNone, and for each dish printcookedand its name.Write
async def run_kitchen(dishes, cooks): put every dish in anasyncio.Queue, startcooksconsumer tasks that each take dishes until the queue is empty (useget_nowait()and stop onasyncio.QueueEmpty), and return the list of every dish made, sorted.