Concurrency with asyncio
One thread, many tasks: how awaiting overlaps waits, turning ten seconds into five.
- Define coroutines with async def and pause them with await
- Run coroutines concurrently with asyncio.gather
- Know which workloads asyncio speeds up and which it cannot
A coroutine, defined with async def, is a function that can pause. Every await is a point where it says “I am waiting — run something else”. The event loop, started by asyncio.run, keeps a list of paused coroutines and resumes each one when the thing it waits for is ready.
f_async.py builds up in three steps. First, a single coroutine sleeps a second and prints. Then two counters run together:
async def count_up():
for i in range(1, 6):
await asyncio.sleep(1)
print(f'Counting up: {i}')
async def main():
await asyncio.gather(count_up(), cound_down())
Measured: under gather, the prints arrive in pairs at 1, 2, 3, 4 and 5 seconds and the program finishes in 5.0 s. Awaiting count_up() and then cound_down() takes 10.0 s. Nothing ran in parallel — there is still one thread — but the waiting did overlap, and waiting was all these coroutines were doing.
That is the whole point of asyncio: it speeds up programs that spend their time waiting — on the network, a disk or a timer. The third example fetches two URLs with aiohttp concurrently; ten requests that each take 200 ms finish in about 200 ms instead of two seconds. CPU-bound work gains nothing, because a coroutine doing arithmetic never reaches an await to let others run; that calls for processes or a GPU (lesson 12).
Two practical notes. The script imports aiohttp on its first line, so without pip install aiohttp it fails before even the first, library-free example runs — moving the import into the third example keeps the first two runnable. And calling a coroutine function without await, as in plain count_up(), only creates a coroutine object; Python warns that it “was never awaited” and nothing happens.
Try it yourself. Replace asyncio.sleep(1) with time.sleep(1) in both counters and time the gather version. Explain the result. Then use asyncio.create_task to start count_up in the background and print something else while it runs.