Python 3D Academyবাংলা

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 waiting await raises asyncio.CancelledError

How a blocking call freezes everything, step by step:

  1. gather starts tea and toast
  2. tea calls time.sleep(0.3); there is no await, so control never goes back to the loop
  3. toast can't even start until tea's sleep is over
  4. 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())
Here the two calls run one after the other. On a computer each waits in its own thread, so ['a saved', 'b saved'] appears after about 0.2 seconds instead of 0.4.

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 without await
  • expecting to_thread to 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 with raise (since Python 3.8 it isn't an Exception, so except Exception lets it through, but a bare except: catches it)
  • cancel() only asks: the task stops at its next await; once a coroutine is running, it can't be stopped until it reaches an await

Quiz

  1. 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())
  2. Inside a coroutine, which line blocks the event loop?

    • time.sleep(1)
    • await asyncio.sleep(1)
    • await asyncio.to_thread(time.sleep, 1)
  3. 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())
  4. 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
  5. 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

  1. cook writes what it does into log, but it waits with time.sleep, so gather can't overlap the dishes. Fix cook so the waits overlap: toast (0.01 s) should finish before tea (0.03 s). Use asyncio's own sleep: here to_thread can't run the waits side by side, because the browser's Python has no threads.

  2. forever() ticks into log until it is stopped. Write async def stop_after(secs): start forever() as a task, wait secs seconds, cancel it, await it (catching asyncio.CancelledError), and return task.cancelled().