Python theorytheory 0/50 · 0%
Async · hard

39. Async/await with asyncio

Cooperative concurrency for I/O-bound code.

`asyncio` provides cooperative concurrency: coroutines defined with `async def` voluntarily yield control at `await` points, letting the event loop run other coroutines while waiting on I/O.

python
import asyncio

async def fetch(name, delay):
    await asyncio.sleep(delay)
    return f"{name} done"

async def main():
    results = await asyncio.gather(
        fetch("chainA", 1),
        fetch("chainB", 0.5),
    )
    return results

asyncio.run(main())

`asyncio.gather` runs coroutines concurrently and collects results in order; unlike threads, only one coroutine actually executes Python code at any instant — concurrency comes from overlapping wait times, not parallel CPU execution.

Check your understanding

  1. 1. What does `await` do inside a coroutine?

  2. 2. What does `asyncio.gather(a, b)` do?

  3. 3. Where does asyncio's concurrency come from, since only one coroutine runs at a time?