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 concurrently with create_task and gather. It also assumes you know the difference between I/O-bound and CPU-bound work. Here you will learn how to run code that cannot await without freezing every other task.
Why one blocking call stalls everything
The event loop runs on one thread. It can switch between tasks only when a task reaches an await and hands control back. A call that does not yield, such as time.sleep, requests.get, a large file read, or a tight computation, keeps the thread busy. No other task runs until it returns. Timers, network callbacks, and other tasks all wait.
import asyncio
import time
async def ticker(start):
for _ in range(3):
print(f"tick at {time.perf_counter() - start:.1f}s")
await asyncio.sleep(0.3)
async def main():
start = time.perf_counter()
task = asyncio.create_task(ticker(start))
await asyncio.sleep(0) # let the ticker run its first tick
time.sleep(1) # blocks the whole loop
await task
asyncio.run(main())You expect ticks 0.3 seconds apart. The first tick prints at 0.0s. The second prints at about 1.0s, because the loop was frozen for the full second. Nothing raises an error, and the program still gives correct results. It just loses its concurrency.
Decide what kind of blocking you have
The fix depends on why the call blocks.
| Situation | Best option | Why |
|---|---|---|
| An async library exists (for example an async HTTP or database client) | Use it with `await` | No extra threads, and cancellation works properly |
| Blocking I/O with no async version (a sync SDK, `requests`, file access) | `asyncio.to_thread` | Threads release the GIL while waiting on I/O |
| CPU-bound pure Python work | `ProcessPoolExecutor` via `run_in_executor` | Separate processes sidestep the GIL |
| Native code that releases the GIL (some NumPy and compression routines) | `to_thread` | Threads can run it in parallel |
The GIL (global interpreter lock) lets only one thread execute Python bytecode at a time. A thread waiting on a socket or time.sleep releases it, so I/O work benefits from threads. A thread doing pure-Python arithmetic holds it, so extra threads add nothing for CPU-bound work, and the computation still competes with the event loop thread.
Offloading with asyncio.to_thread
asyncio.to_thread(func, *args, **kwargs) runs func in a worker thread and returns an awaitable. The loop keeps running other tasks 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 ticker prints three times at 0.3-second intervals while the blocking function sleeps. The program finishes after about one second and prints done.
Some details about to_thread:
- It accepts keyword arguments directly:
await asyncio.to_thread(read_file, path, encoding="utf-8"). - It copies the current
contextvarscontext into the thread, so request IDs and similar values stay visible. - It returns the function's return value, and it re-raises any exception the function raised, at the
await. - It requires Python 3.9 or later.
Executors and run_in_executor
to_thread is a convenience over the loop's default executor, which is a ThreadPoolExecutor. The lower-level API is loop.run_in_executor(executor, func, *args). It takes only positional arguments, so wrap keyword arguments with functools.partial. Passing None as the executor uses the default one.
You need run_in_executor for a process pool, which is the right tool for CPU-bound work.
import asyncio
import concurrent.futures
import hashlib
def slow_hash(text):
data = text.encode()
for _ in range(200_000):
data = hashlib.sha256(data).digest()
return data.hex()
async def main():
loop = asyncio.get_running_loop()
with concurrent.futures.ProcessPoolExecutor() as pool:
results = await asyncio.gather(
*(loop.run_in_executor(pool, slow_hash, word) for word in ["a", "b", "c"])
)
print([r[:8] for r in results])
if __name__ == "__main__":
asyncio.run(main())The if __name__ == "__main__": guard is required. On platforms that start worker processes by importing your module (Windows, and macOS by default), a missing guard makes each worker re-run the program. Arguments and return values are pickled, so the function must be defined at module top level, and the data must be picklable and reasonably small.
Sizing the default thread pool
The default executor has min(32, os.cpu_count() + 4) threads. If you start hundreds of to_thread calls, most queue behind the first few. To change the limit, install your own executor once at startup:
import asyncio
from concurrent.futures import ThreadPoolExecutor
async def main():
loop = asyncio.get_running_loop()
loop.set_default_executor(ThreadPoolExecutor(max_workers=8, thread_name_prefix="blocking"))
results = await asyncio.gather(*(asyncio.to_thread(pow, 2, n) for n in range(5)))
print(results)
asyncio.run(main())Do not size the pool to match task counts. Use it to cap the load you put on the system, such as the number of simultaneous connections to a sync client library. An asyncio.Semaphore around the to_thread call gives you the same cap for one specific resource.
Edge cases and failure modes
Cancellation does not stop the thread. Cancelling a task awaiting to_thread raises CancelledError at the await, but Python cannot kill a running thread. The function runs to completion and its result is discarded. Timeouts have the same effect: asyncio.timeout unblocks your coroutine, not the worker. For long jobs, have the function check a threading.Event and return early.
Shutdown waits for threads. asyncio.run waits for the default executor to finish before it returns. A thread stuck in a blocking call can make the program hang at exit.
Thread safety is your job. The function runs in another thread, so it must not touch asyncio objects such as tasks, queues, or futures. Those are not thread-safe. To hand a result back, return it, or call loop.call_soon_threadsafe(...) or asyncio.run_coroutine_threadsafe(coro, loop) from the thread. Shared plain data still needs ordinary locks.
Never call result() or time.sleep to "wait" in a coroutine. Both block the loop. Use await on the future, or await asyncio.sleep.
Hidden blocking. Blocking can come from places that do not look like I/O. Examples are socket.getaddrinfo in sync code, open().read() on a slow network drive, a heavy json.loads, regex backtracking, or a library that calls requests internally. If the call takes noticeable time and has no await, treat it as blocking.
Finding blocking calls
Debug mode reports any callback that holds the loop for more than loop.slow_callback_duration, which defaults to 0.1 seconds.
import asyncio
import time
async def main():
time.sleep(0.5) # accidental blocking call
asyncio.run(main(), debug=True)The log shows a warning like Executing <Task ...> took 0.500 seconds, including the task and its location. You can also set the environment variable PYTHONASYNCIODEBUG=1. Debug mode adds overhead, so use it in development and tests, not in production.
Summary of decisions
- Prefer a native async library when one exists.
- Use
asyncio.to_threadfor blocking I/O and for native code that releases the GIL. - Use
run_in_executorwith aProcessPoolExecutorfor CPU-bound Python. - Cap concurrency with a sized executor or a semaphore.
- Plan for cancellation: the awaiting coroutine stops, the thread does not.
- Use debug mode to find calls you did not know were blocking.
Exercise
A coroutine calls requests.get(url) (a sync HTTP client) and, a few lines later, compress(data), a pure-Python function that takes about five seconds of CPU time. Both calls freeze other tasks. How would you fix each one, and what happens to the worker if the surrounding task is cancelled during the requests.get call?
Show answer
Wrap requests.get with await asyncio.to_thread(requests.get, url), because it is blocking I/O and threads release the GIL while waiting on the network. Run compress in a process pool with await loop.run_in_executor(pool, compress, data), because pure-Python CPU work holds the GIL and threads would not help. Keep the function at module level, keep the arguments picklable, and put asyncio.run under an if __name__ == "__main__": guard. If the task is cancelled during requests.get, the await raises CancelledError, but the worker thread keeps running until the request finishes, and its result is discarded.
Exercise
You run await asyncio.gather(*(asyncio.to_thread(fetch, u) for u in urls)) with 500 URLs and notice only about a dozen requests run at a time. Why, and how can you change it?
Show answer
to_thread uses the loop's default thread pool, which has min(32, os.cpu_count() + 4) workers, so the remaining calls queue. To raise or lower the limit, call loop.set_default_executor(ThreadPoolExecutor(max_workers=N)) once at startup. To cap concurrency for one resource, wrap each call in an asyncio.Semaphore. Whether more threads help depends on the remote service and your system limits.