Don't block the loop: blocking calls, to_thread and cancelling
🌍 In real life. A restaurant's single cook switches between dishes: stir the dal, check the rice, flip the egg. If the cook stops to stare at the oven for ten minutes, every other dish burns and every order waits. The fix is to set a timer and keep switching, or to hand the oven to a helper.
The idea in one sentence: anything that waits without await (like time.sleep, a slow loop, or a library that isn't async) blocks the event loop: no other coroutine can run until it ends, so gather and tasks stop helping.
Its words:
- blocking call: a call that waits or works for a long time without ever awaiting
- non-blocking: waits with
await, so the loop can switch asyncio.to_thread(f, ...): runs a normal blocking function in a separate thread, and lets you await its result, so the loop stays free- cancelling:
task.cancel()asks a task to stop; inside it, the waitingawaitraisesasyncio.CancelledError
How a blocking call freezes everything, step by step:
- gather starts tea and toast
- tea calls
time.sleep(0.3); there is no await, so control never goes back to the loop - toast can't even start until tea's sleep is over
- the total is 0.3 + 0.1, as if there were no gather at all
The red bars are Python busy inside time.sleep, holding the loop:
Why it happens. The event loop is one worker taking turns, and it only gets the worker back at an await (Lesson 32.1). time.sleep is an ordinary function: it holds on to the worker until the time is up. So does a long calculation, or requests.get from a library written before asyncio. The loop isn't broken; it simply never gets a turn.
What to do instead:
- for waiting, use the async version:
await asyncio.sleep(...), or an async library for the network (such as httpx or aiohttp) - for a blocking function you can't change,
await asyncio.to_thread(f, args)runs it in a separate thread while the loop carries on (on a computer; the browser's Python has no threads); it suits waiting (files, old libraries), not heavy calculating, because of the GIL (Lesson 32.4)
The browser's Python has no threads, so here each call simply runs on the spot, one after the other; what it prints is the same:
import asyncio
import time
def old_download(name): # a blocking function we can't change
time.sleep(0.2)
return name + " saved"
async def main():
results = await asyncio.gather(
asyncio.to_thread(old_download, "a"),
asyncio.to_thread(old_download, "b"),
)
print(results)
asyncio.run(main())Cancelling a task. Sometimes you stop waiting on purpose: the user pressed Cancel, or a faster answer came in. task.cancel() doesn't kill the task on the spot. It marks it, and the next time the task is waiting at an await, that await raises asyncio.CancelledError inside it. The error travels up like any other (Lesson 18.4), so finally blocks run and the task can clean up. Awaiting a cancelled task raises CancelledError in the awaiter too:
import asyncio
async def download(name):
try:
print("start", name)
await asyncio.sleep(10)
print("done", name) # never reached
finally:
print("clean up", name)
async def main():
task = asyncio.create_task(download("movie"))
await asyncio.sleep(0.05) # let it start
task.cancel()
try:
await task
except asyncio.CancelledError:
print("cancelled:", task.cancelled())
asyncio.run(main())What it costs, by counting. With blocking waits, gather costs the sum: 0.3 + 0.1 = 0.4 s for tea and toast, and 100 requests that each block for 0.5 s take 50 s. With awaiting waits it costs the longest: 0.3 s, and the 100 requests take about 0.5 s. One hidden blocking call in a busy server delays every other user for as long as it runs.
Mistakes and edge cases.
- hidden blocking:
time.sleep,requests.get, a big file read or a long loop inside a coroutine; look for calls withoutawait - expecting
to_threadto speed up calculating: threads take turns on the GIL, so heavy number work needs processes (Lesson 32.4) - swallowing CancelledError: catching it and carrying on means the task can never be stopped; clean up in
finally, or re-raise withraise(since Python 3.8 it isn't an Exception, soexcept Exceptionlets it through, but a bareexcept:catches it) cancel()only asks: the task stops at its nextawait; once a coroutine is running, it can't be stopped until it reaches anawait
Quiz
What does this print?
import asyncio import time async def job(name): print("start", name) time.sleep(0.01) print("end", name) async def main(): await asyncio.gather(job("a"), job("b")) asyncio.run(main())Inside a coroutine, which line blocks the event loop?
- time.sleep(1)
- await asyncio.sleep(1)
- await asyncio.to_thread(time.sleep, 1)
What does this print?
import asyncio async def slow(): try: await asyncio.sleep(5) except asyncio.CancelledError: print("cleaning up") raise async def main(): t = asyncio.create_task(slow()) await asyncio.sleep(0) t.cancel() try: await t except asyncio.CancelledError: print("main saw it") asyncio.run(main())After task.cancel(), when does the task actually stop?
- At its next await, which raises CancelledError inside it
- Instantly, in the middle of any line
- Only when the program ends
This worker should clean up and stop when it is cancelled, but it never stops. Which line is wrong?
import asyncio async def worker(): while True: try: await asyncio.sleep(1) except asyncio.CancelledError: print("cleaning up") continue
Coding tasks
cookwrites what it does intolog, but it waits withtime.sleep, sogathercan't overlap the dishes. Fixcookso the waits overlap: toast (0.01 s) should finish before tea (0.03 s). Use asyncio's own sleep: hereto_threadcan't run the waits side by side, because the browser's Python has no threads.forever()ticks intologuntil it is stopped. Writeasync def stop_after(secs): startforever()as a task, waitsecsseconds, cancel it, await it (catchingasyncio.CancelledError), and returntask.cancelled().