Sub topic 1
Why asyncio: concurrency for I/O-bound programs
Prerequisites
This chapter assumes you can write Python functions, classes, and context managers. You should also know how try/except works and what generators and iterators are. Basic familiarity with the difference between I/O-bound and CPU-bound work helps, and the next section reviews it.
The problem: programs that wait
Many programs spend most of their time waiting. A web client waits for a server to answer. A script that reads from a database waits for rows to arrive. During that wait the CPU has nothing to do.
Work like this is I/O-bound: its speed is limited by input and output, not by computation. Work that keeps the processor busy, such as resizing images or computing hashes, is CPU-bound.
Run I/O-bound tasks one after another and the waits add up. Ten requests that each take one second finish in ten seconds, even though the processor was nearly idle the whole time.
Concurrency and parallelism
These two terms are often confused.
- Concurrency means managing several tasks whose lifetimes overlap. They do not need to run at the same instant.
- Parallelism means executing several tasks at the same instant, on several CPU cores.
asyncio gives you concurrency on a single thread. While one operation waits for I/O, the program switches to another operation that is ready. It does not make Python code run faster on multiple cores.
Choosing a concurrency model
Python offers three common approaches. Each one fits a different kind of problem.
| Model | How it works | Best for | Main cost |
|---|---|---|---|
| `asyncio` | One thread, tasks switch at `await` points | Many simultaneous I/O waits, such as network connections | Code must be written in the async style |
| Threads | The operating system switches between threads | I/O-bound work with blocking libraries | Shared data needs locks, and each thread uses memory |
| Processes | Separate interpreters on separate cores | CPU-bound work | Startup cost and data must be copied between processes |
The main advantage of asyncio is scale. A task is a small Python object, so a program can hold thousands of open connections without thousands of threads. Because tasks switch only at await, you also avoid many of the race conditions that threads cause.
What it looks like
The sketch below shows the idea. The await asyncio.sleep(1) line stands in for any slow I/O call. Three of them overlap, so the program takes about one second instead of three.
import asyncio
import time
async def fetch(n):
await asyncio.sleep(1)
return n * 2
async def main():
start = time.perf_counter()
results = await asyncio.gather(fetch(1), fetch(2), fetch(3))
elapsed = time.perf_counter() - start
print(results, f"{elapsed:.1f}s")
asyncio.run(main())It prints [2, 4, 6] and a time near 1.0s. Later chapters explain each piece. For now, notice that nothing here uses threads.
Common errors in the mental model
- Expecting a speedup for CPU-bound code. A long calculation inside a coroutine never reaches an
await, so it blocks every other task. Use processes for that kind of work. - Using blocking calls. A call such as
time.sleep(1)freezes the whole program for that second. Useawait asyncio.sleep(1)or an async library instead. - Thinking
async defalone creates concurrency. Concurrency appears only when several tasks are scheduled and each one awaits something.
Exercise
A program downloads 200 small files and spends 95% of its time waiting for the network. Is it I/O-bound or CPU-bound, and why would asyncio help?
Show answer
It is I/O-bound, since the network limits its speed. With asyncio, the program can start other downloads while one waits for data. The waits overlap, so total time approaches that of the slowest downloads instead of the sum of all of them.
Exercise
Why does asyncio not speed up a loop that hashes a large file for ten seconds?
Show answer
Hashing is CPU-bound and never reaches an await, so the event loop cannot switch to other work. Asyncio runs on one thread, so it cannot use extra cores. Multiple processes would help instead.