Sub topic 12
asyncio in brief: cooperative concurrency on one thread
This chapter assumes you have read the earlier chapters on threads, the GIL, and the difference between I/O-bound and CPU-bound work. You should know what a blocking call is. You should also be comfortable with def functions, context managers, and Python 3.11 or later. TaskGroup and asyncio.timeout need 3.11.
The third option
Threads and processes let the operating system decide when your tasks run. asyncio takes a different approach. A single thread runs an event loop, and each task decides for itself when to pause. A task pauses at an await expression, and the loop then runs another task that is ready.
This is cooperative multitasking. Nothing interrupts a task. A task that never reaches an await keeps the loop, and every other task, waiting.
asyncio targets the same kind of work that threads handle well, which is I/O-bound work. Its advantage is cost. A task is a small Python object, not an OS thread. A single process can hold tens of thousands of tasks, such as network connections that are mostly idle.
The vocabulary
- A coroutine function is defined with
async def. Calling it returns a coroutine object and does not run any of its body. - A coroutine runs only when something drives it. You can
awaitit, wrap it in a task, or pass it toasyncio.run. - A task is a coroutine scheduled on the event loop.
asyncio.create_taskandasyncio.gathercreate tasks. - The event loop is the scheduler. It keeps the tasks that are ready to run and the tasks that are waiting for I/O or a timer.
awaitmeans "wait for this result and let the loop run other tasks meanwhile."
A first example
This is the same experiment as the thread-pool example earlier in the tutorial. It runs five one-second waits.
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():
return await asyncio.gather(*(fake_download(n) for n in range(5)))
start = time.perf_counter()
results = asyncio.run(main())
print(results, f"{time.perf_counter() - start:.1f}s")The output is [0, 2, 4, 6, 8] 1.0s. All five tasks reach await asyncio.sleep(1) almost immediately. The loop then has nothing to run until the timers expire, so the waits overlap. gather returns results in the order you passed the awaitables, not in completion order.
asyncio.run creates a loop, runs the coroutine until it finishes, and closes the loop. Call it once, at the top level of your program.
Structured concurrency with TaskGroup
gather is fine for simple cases. When one task fails, though, the others keep running unless you cancel them yourself. Since Python 3.11, asyncio.TaskGroup handles this. The async with block waits for all of its tasks. If one raises an exception, it cancels the rest and re-raises the error as an ExceptionGroup.
import asyncio
async def fetch(name, delay, fail=False):
await asyncio.sleep(delay)
if fail:
raise ValueError(f"{name} failed")
return name
async def main():
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(fetch("a", 0.1))
tg.create_task(fetch("b", 0.2, fail=True))
slow = tg.create_task(fetch("c", 5))
except* ValueError as eg:
print("caught:", [str(e) for e in eg.exceptions])
print("slow task cancelled:", slow.cancelled())
asyncio.run(main())Task c would take five seconds. It is cancelled when b fails, so the program ends after about 0.2 seconds. The except* syntax matches exceptions inside an ExceptionGroup.
For a time limit, use async with asyncio.timeout(2):. It cancels the enclosed block and raises TimeoutError if the block runs past two seconds.
The cardinal rule: never block the loop
Every other task is stalled while one task runs without reaching an await. This is the most common asyncio error. These calls are the usual causes:
time.sleepinstead ofasyncio.sleep- the
requestslibrary, which blocks on the network - synchronous database drivers
- reading large files
- any long computation
Here time.sleep(1) appears in a coroutine. Five such tasks take about five seconds, not one, because each holds the thread while it sleeps.
If the work has no async version, move it off the loop thread. asyncio.to_thread runs a function in a worker thread and gives you something to await.
import asyncio
import time
def blocking_job():
time.sleep(1) # a blocking call we cannot rewrite
return "done"
async def ticker():
for i in range(3):
print("tick", i)
await asyncio.sleep(0.4)
async def main():
background = asyncio.create_task(ticker())
result = await asyncio.to_thread(blocking_job)
await background
print(result)
asyncio.run(main())The ticks print while the blocking job runs, because the job sits in another thread and the loop stays free. This works for I/O-bound blocking calls, since the GIL is released while a thread waits. It does not give you CPU parallelism. For CPU-bound work, use a process pool.
import asyncio
from concurrent.futures import ProcessPoolExecutor
def count_down(n):
while n > 0:
n -= 1
return n
async def main():
loop = asyncio.get_running_loop()
with ProcessPoolExecutor(max_workers=4) as pool:
jobs = [loop.run_in_executor(pool, count_down, 10_000_000) for _ in range(4)]
print(await asyncio.gather(*jobs))
if __name__ == "__main__":
asyncio.run(main())The __main__ guard is needed here for the same reason as in the earlier process chapters. Under the spawn start method, each worker re-imports the module.
Shared state is safer, but not safe
On a single thread, no two tasks run at the same instant. Code between two await points runs without interruption. This removes many of the races you saw with threads. For example, counter += 1 with no await inside is safe.
The problem returns when you await between a read and the write that depends on it. At that point other tasks can run.
import asyncio
balance = 100
lock = asyncio.Lock()
async def withdraw(amount):
global balance
async with lock: # remove this line to see the lost update
current = balance
await asyncio.sleep(0) # yields to the loop
balance = current - amount
async def main():
await asyncio.gather(withdraw(30), withdraw(50))
print(balance) # 20
asyncio.run(main())Without the lock, both tasks read 100. One writes 70, the other writes 50, and the program prints 50. With the lock, it prints 20. Use asyncio.Lock, not threading.Lock. A threading lock blocks the whole thread, so the task that holds it could never resume to release it, and the program would deadlock. Neither lock type is safe to share across the two worlds. Do not use asyncio.Lock from other threads.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `RuntimeWarning: coroutine ... was never awaited` | You called an `async def` function and did not `await` it or schedule it | Add `await`, or wrap it in `create_task` |
| `RuntimeError: asyncio.run() cannot be called from a running event loop` | Nested `asyncio.run`, common in notebooks | `await` the coroutine directly |
| Tasks run one after another | You wrote `await f(); await g()` | Use `gather` or a `TaskGroup` |
| The whole program freezes | A blocking call or a long loop inside a coroutine | `to_thread` or a process pool |
| A task disappears silently | You discarded the return value of `create_task`, and the loop holds only a weak reference | Keep a reference, or use a `TaskGroup` |
For debugging, run with python -X dev or asyncio.run(main(), debug=True). The loop then logs any callback that blocks it for more than 100 ms.
Where asyncio fits
Compare it with the other models from this tutorial.
| Row | Threads | Processes | asyncio |
|---|---|---|---|
| Scheduling | Preemptive, by the OS | Preemptive, by the OS | Cooperative, at `await` |
| CPU-bound speedup (GIL build) | No | Yes | No |
| Cost per unit of work | Thread stack, OS limits | Whole interpreter | A small object |
| Race risk | At any bytecode boundary | None for unshared memory | Only across `await` |
| Needs async-aware libraries | No | No | Yes |
The last row is the main cost of asyncio. Every library on the path must offer an async interface, or you must wrap it in to_thread. For a few dozen concurrent downloads, a thread pool is simpler and just as fast. For thousands of mostly idle connections, asyncio is the better fit.
Exercise
A coroutine downloads a page with the blocking requests.get(url). You start 20 of these with asyncio.gather. The run takes about 20 times longer than one download. Why, and what are two ways to fix it?
Show answer
requests.get blocks the single event-loop thread, and there is no await to let other tasks run, so the downloads run one at a time. One fix is to wrap each call with await asyncio.to_thread(requests.get, url), so the blocking call runs in worker threads. The other is to switch to an async-native HTTP client, so the wait becomes an await and the loop can overlap the downloads.
Exercise
In an async def function, x = shared["n"], then await asyncio.sleep(0), then shared["n"] = x + 1. Why is this unsafe with several tasks running it, even though there is only one thread? What fixes it?
Show answer
The await lets the loop run other tasks between the read and the write. Two tasks can read the same value, so one of the increments is lost. Wrap the read-modify-write sequence in async with asyncio.Lock():. You could also restructure the code so that no await sits between the read and the write.