Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 13 / Topic 8 of 11

Running many coroutines

asyncio.gather

gather runs several coroutines together and returns their results as a list, in the same order you passed them (not the finish order). Like ordering from three counters in a food court at once, then collecting your tray in the order you listed.

import asyncio

async def cook(dish: str, seconds: float) -> str:
    await asyncio.sleep(seconds)
    return dish

async def main() -> None:
    dishes = await asyncio.gather(cook("biryani", 0.3), cook("dosa", 0.1))
    print(dishes)                     # ['biryani', 'dosa']   (~0.3 s, not 0.4 s)

asyncio.run(main())

asyncio.TaskGroup (3.11+)

A task is a coroutine that the event loop has started running. TaskGroup is the modern, safer way to run many tasks: the async with block waits for all of them, and if one fails, the others are cancelled and the error is raised.

import asyncio

async def cook(dish: str, seconds: float) -> str:
    await asyncio.sleep(seconds)
    return dish

async def main() -> None:
    async with asyncio.TaskGroup() as group:
        first = group.create_task(cook("poha", 0.2))
        second = group.create_task(cook("upma", 0.1))
    # here every task is finished
    print(first.result(), second.result())      # poha upma

asyncio.run(main())

If one task fails, the error comes out as an ExceptionGroup (Part 15); catch it with except* ValueError:. For simple scripts, gather is fine.

asyncio.timeout()

asyncio.timeout(seconds) (3.11+) cancels whatever is inside the block if it takes too long, and raises TimeoutError.

import asyncio

async def main() -> None:
    try:
        async with asyncio.timeout(0.1):
            await asyncio.sleep(5)            # a very slow API
    except TimeoutError:
        print("gave up after 0.1 s")          # gave up after 0.1 s

asyncio.run(main())

Cancellation basics

task.cancel() asks a task to stop. Python raises asyncio.CancelledError inside the task at its current await. You may catch it to clean up, but then re-raise it.

import asyncio

async def track_rider() -> None:
    try:
        while True:
            await asyncio.sleep(0.05)
    except asyncio.CancelledError:
        print("cleaning up")
        raise                                 # let the cancel finish

async def main() -> None:
    task = asyncio.create_task(track_rider())  # start it in the background
    await asyncio.sleep(0.1)
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print("cancelled:", task.cancelled())

asyncio.run(main())
# cleaning up
# cancelled: True

Full program: examples/06_asyncio_basics.py (one by one ~0.6 s vs gather ~0.3 s vs TaskGroup ~0.3 s, a timeout and a cancel).

๐Ÿ” Going deeper: keep a reference to every task you make with asyncio.create_task (in a variable or list). The event loop only keeps a weak reference, so an unreferenced task can disappear before it finishes. TaskGroup keeps them for you.

Done here? The practice set for Part 13 โ€” 8 exercises with solutions โ€” is on the part page.

Search the guide