Sub topic 13
Keeping blocking calls off the event loop
This chapter assumes you can write coroutines, start them with asyncio.run, and run them together with gather. It also assumes you know the difference between I/O-bound and CPU-bound work.
Why one blocking call hurts everything
The event loop runs on a single thread. It switches between tasks only when a task reaches an await. A call such as time.sleep(1), a synchronous HTTP request, or a slow file read never yields control. While it runs, every other task is frozen: timers don't fire, and network data waits unread.
This is the most common asyncio bug. The program still produces correct results. It just loses all of its concurrency.
Moving blocking work into a thread
asyncio.to_thread(func, *args) runs a normal function in a worker thread and returns an awaitable. The loop stays free while the thread works.
import asyncio
import time
def blocking_io():
time.sleep(1)
return "done"
async def ticker():
for _ in range(3):
print("tick")
await asyncio.sleep(0.3)
async def main():
result, _ = await asyncio.gather(asyncio.to_thread(blocking_io), ticker())
print(result)
asyncio.run(main())The three tick lines print while blocking_io sleeps, and done prints after about one second. If you replaced the to_thread call with a direct blocking_io() call, the ticks would wait for the full second.
Pass arguments to to_thread instead of calling the function yourself. Write asyncio.to_thread(fetch, url), not asyncio.to_thread(fetch(url)). The second form runs fetch on the loop first and hands its result to the thread.
Threads versus processes
A thread helps when the blocking code spends its time waiting, as in file access, a legacy database driver, or a synchronous HTTP library. These calls release Python's global interpreter lock (GIL) while they wait.
Pure Python computation holds the GIL. A thread keeps the loop responsive, but the work doesn't run any faster, and it can still slow the loop. For heavy CPU work, use a process pool through loop.run_in_executor.
| Kind of work | Tool | Reason |
|---|---|---|
| Waiting on blocking I/O | `asyncio.to_thread` | The thread sleeps and releases the GIL |
| Heavy computation | `ProcessPoolExecutor` with `run_in_executor` | Separate processes avoid the GIL |
| Async-native library exists | Use it directly | No thread overhead |
import asyncio
from concurrent.futures import ProcessPoolExecutor
def crunch(n):
return sum(i * i for i in range(n))
async def main():
loop = asyncio.get_running_loop()
with ProcessPoolExecutor() as pool:
result = await loop.run_in_executor(pool, crunch, 5_000_000)
print(result)
if __name__ == "__main__":
asyncio.run(main())The if __name__ == "__main__" guard is required, because worker processes may import the module again. Arguments and return values must be picklable.
Common errors
- Calling
time.sleepinside a coroutine. Useawait asyncio.sleepinstead. - Using a synchronous library such as
requestsin a coroutine. Wrap the call into_threador switch to an async library. - Touching loop-bound objects from a worker thread. Code inside
to_threadshould not create tasks or await anything. - Assuming a thread can be cancelled. Cancelling the awaiting task stops the wait, but the thread keeps running until the function returns.
Exercise
A coroutine calls data = requests.get(url) and the other tasks stall while it runs. Write the one-line change that keeps the loop responsive, and say why it works.
Show answer
data = await asyncio.to_thread(requests.get, url). The blocking call now runs in a worker thread, and the coroutine suspends at await, so the event loop can run other tasks until the thread finishes.
Exercise
You need to hash a very large file with a pure Python loop. Should you use to_thread or a process pool, and why?
Show answer
Use a process pool with run_in_executor. The loop is CPU-bound and holds the GIL, so a thread would not run it in parallel and could still slow the event loop. A separate process has its own GIL.