Python 3D Academyবাংলা

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 a maxsize, await put(...) waits while the queue is full
  • queue.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:

  1. Three slips go on the rail: tea, toast, egg.
  2. Ana takes tea and Bo takes toast; both cook at the same time.
  3. Ana finishes first, marks tea done, and takes egg.
  4. Bo finishes toast and waits: the rail is empty.
  5. 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())
The rail never holds more than 2 slips: once it is full, the waiter's put waits for the cook. That is backpressure.

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 missing task_done() makes it wait for ever. (Here, press Stop.)
  • Forgetting await. dish = orders.get() gives a coroutine object, not an item. Write dish = await orders.get().
  • One sentinel for several consumers. Each consumer stops at the None it takes, so two consumers need two Nones; with one, the second waits for ever.
  • The _nowait versions don't wait. put_nowait on a full queue raises asyncio.QueueFull, and get_nowait on an empty one raises asyncio.QueueEmpty.
  • Consumers that never stop. A while True consumer runs until it is cancelled. Cancel it, or send a sentinel.

Quiz

  1. 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
  2. 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
  3. 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())
  4. 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())
  5. 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

  1. Write the consumer cook(orders): take dishes from the queue until it gets None, and for each dish print cooked and its name.

  2. Write async def run_kitchen(dishes, cooks): put every dish in an asyncio.Queue, start cooks consumer tasks that each take dishes until the queue is empty (use get_nowait() and stop on asyncio.QueueEmpty), and return the list of every dish made, sorted.