Sub topic 12
asyncio in brief: cooperative concurrency on one thread
This chapter assumes you know async def and await syntax at a basic level. It also assumes you have read the earlier chapters on threads, the GIL, and I/O-bound versus CPU-bound work.
The model
asyncio runs many tasks on a single thread. A task is a coroutine (the object an async def function returns) that the event loop schedules. The loop runs one task until it reaches an await on something that is not ready yet, such as a network read or a sleep. At that point the task hands control back, and the loop runs another task.
This is cooperative scheduling. Threads are preempted by the interpreter at almost any point. An asyncio task is interrupted only where it writes await. Because only one task runs at a time, the GIL does not matter here, and there is no thread switching to pay for.
A first example
This is the same workload as the thread pool example from earlier, written with asyncio.
import asyncio
import time
async def fake_download(n):
await asyncio.sleep(1) # stands in for waiting on the network
return n * 2
async def main():
start = time.perf_counter()
results = await asyncio.gather(*(fake_download(n) for n in range(5)))
print(results, f"{time.perf_counter() - start:.1f}s")
asyncio.run(main())asyncio.run starts the loop and runs main to completion. asyncio.gather schedules all five coroutines at once and returns their results in order. The total time is about one second, because all five sleeps overlap.
Threads versus asyncio
| Row | Threads | asyncio |
|---|---|---|
| Switching | Preemptive, at almost any point | Cooperative, only at `await` |
| Shared-state races | Possible, so locks are needed | Rare, since code between awaits runs uninterrupted |
| Scale | Hundreds, limited by memory | Tens of thousands of tasks |
| Needs async-aware libraries | No | Yes |
| CPU-bound speedup | None with the GIL | None |
Races are rarer in asyncio, but they still happen. If you read a value, await, and then write it back, another task may have changed the value in between.
The main mistake: blocking the loop
A blocking call inside a coroutine stops the entire loop, because no other task can run until it returns. time.sleep, requests.get, and a long computation all do this. Use the async equivalent (asyncio.sleep, an async HTTP client), or move the blocking call to a thread with asyncio.to_thread.
import asyncio
import time
def blocking_job():
time.sleep(1) # blocking call, so it must not run on the loop thread
return "done"
async def ticker():
for _ in range(3):
print("tick")
await asyncio.sleep(0.4)
async def main():
result, _ = await asyncio.gather(asyncio.to_thread(blocking_job), ticker())
print(result)
asyncio.run(main())The ticks keep printing while blocking_job runs in a worker thread. If you replaced asyncio.to_thread(blocking_job) with a direct blocking_job() call, the ticker would stall for the full second.
When to choose it
Choose asyncio when you have many concurrent I/O waits, such as thousands of sockets, and your libraries support await. Choose threads when you must call blocking libraries and the number of tasks is modest. Choose processes for CPU-bound work. The later chapter on choosing a model covers how to measure the difference.
Exercise
A coroutine calls time.sleep(2) instead of await asyncio.sleep(2). You run ten of these with asyncio.gather. About how long does the run take, and why?
Show answer
About 20 seconds. time.sleep blocks the only thread, so the event loop cannot switch to another task and the ten sleeps run one after another. With await asyncio.sleep(2) they would overlap and take about 2 seconds.