Sub topic 2
How the event loop schedules work
This chapter assumes you can read basic async def and await code and know what a generator is. You don't need to write coroutines fluently yet. The goal is a working model of what the event loop does between your await points, so that ordering, stalls, and "why did this run now?" questions have clear answers.
One thread, one thing at a time
An asyncio program normally runs on a single thread. At any instant exactly one piece of your code is executing. Concurrency comes from switching between pieces at points you mark with await. This is called cooperative scheduling: the loop never interrupts a running coroutine. A coroutine keeps the thread until it awaits something that cannot complete immediately, or until it returns.
This differs from threads, where the operating system can pause your code between any two bytecode instructions. The consequence is that code between two await expressions runs atomically with respect to other tasks. You rarely need a lock to protect a few lines that contain no await.
The three pieces of state
The default event loop (asyncio.run creates one for you) keeps three things:
- A ready queue. A first-in, first-out list of callbacks that can run right now. Task steps,
call_sooncallbacks, and completed-future callbacks all go here. - A timer heap. Callbacks scheduled for a future time with
call_laterorcall_at, ordered by due time.asyncio.sleepuses this. - A selector. An operating system facility (epoll on Linux, kqueue on macOS and BSD) that reports which sockets and pipes are readable or writable. On Windows the default loop uses I/O completion ports instead, but the model is the same.
One iteration of the loop
The loop repeats the same cycle until it is stopped:
- Choose a wait timeout. If the ready queue has work, the timeout is zero. Otherwise it is the time until the earliest timer. If there are no timers either, the loop waits indefinitely for I/O.
- Ask the selector which file descriptors are ready, waiting up to that timeout. For each ready descriptor, put its registered callback on the ready queue.
- Move every timer whose due time has passed from the heap to the ready queue.
- Run the callbacks that were in the ready queue at this point, one after another, each to completion.
Step 4 has a detail worth remembering. The loop runs only the callbacks that were queued when the step began. A callback that schedules another with call_soon has that new callback run in the next iteration, not in the current one. This prevents a chain of self-rescheduling callbacks from starving I/O polling.
Where tasks fit
A task wraps a coroutine and drives it. Each time the loop runs a task's callback, the task advances the coroutine until it suspends. When the coroutine awaits a pending future, the task registers a callback on that future and returns control to the loop. When the future completes, its callback puts the task's next step back on the ready queue.
So a task is not a thread. It is a coroutine plus a small piece of bookkeeping that says "run me again when this future is done."
What await actually does
await x does one of two things, depending on x:
- If
xis a coroutine,awaitruns it inline, like a function call. Control passes into it immediately. If that coroutine returns without ever suspending, nothing else gets a turn. - If
xis a future (or something that eventually awaits one), and it is not finished, the whole chain of awaiting coroutines suspends and control returns to the loop.
This means await is not automatically a yield to the loop. Only a suspension on an unfinished future gives other tasks a chance. A coroutine that awaits only other coroutines that never suspend behaves exactly like synchronous code.
Yielding explicitly
await asyncio.sleep(0) is the idiom for "let everyone else run once." It suspends the current task for one loop iteration. The next example shows two tasks alternating:
import asyncio
async def worker(name, steps):
for i in range(steps):
print(f"{name} step {i}")
await asyncio.sleep(0)
async def main():
await asyncio.gather(worker("A", 3), worker("B", 3))
asyncio.run(main())The output is A step 0, B step 0, A step 1, B step 1, A step 2, B step 2. gather wraps each coroutine in a task and queues them in argument order. Task A runs until its first sleep(0), then task B runs, and the pattern continues. Remove the await asyncio.sleep(0) line and each worker prints all three steps before the other starts, because nothing ever suspends.
Callbacks, timers, and ordering
You can see the ready queue and timer heap directly through the loop object. This is a low-level interface, and application code rarely needs it. It is useful for understanding order.
import asyncio
async def main():
loop = asyncio.get_running_loop()
loop.call_later(0.2, print, "timer fired")
loop.call_soon(print, "ready callback")
print("before await")
await asyncio.sleep(0.3)
print("after await")
asyncio.run(main())The printed order is before await, ready callback, timer fired, after await. The call_soon callback cannot run while main holds the thread. It runs as soon as main suspends in sleep. The timer is due after 0.2 seconds, and main wakes at 0.3.
Ordering rules you can rely on:
- Callbacks scheduled with
call_soonrun in the order they were scheduled. - Tasks created with
create_taskstart in creation order, but only after the creating coroutine suspends. - Timers run no earlier than their due time. They may run later.
Timers are lower bounds
await asyncio.sleep(1) means "resume me after at least one second." If another callback holds the thread for 400 ms when the timer comes due, the resume is 400 ms late. The loop uses a monotonic clock, so system clock changes do not affect timers. It still cannot preempt running code.
Blocking the loop
Because scheduling is cooperative, a call that blocks the thread blocks every task. The usual causes are time.sleep, synchronous network or file calls, and long CPU loops.
import asyncio
import time
async def ticker():
for _ in range(4):
print("tick")
await asyncio.sleep(0.2)
async def stall():
await asyncio.sleep(0.3)
time.sleep(1) # blocks the whole loop
print("stall finished")
async def main():
await asyncio.gather(ticker(), stall())
asyncio.run(main())You see two ticks, then a one-second pause with no ticks, then stall finished, and the remaining ticks come late. During time.sleep(1) the loop is not in step 2, so no timers are checked and no other task can run. Replace it with await asyncio.sleep(1) and the ticks continue on schedule. Chapter 13 covers moving blocking work off the loop.
Observing slow callbacks
Debug mode reports callbacks that hold the thread too long. Enable it with asyncio.run(main(), debug=True) or the environment variable PYTHONASYNCIODEBUG=1. The loop then logs a warning for any callback that runs longer than loop.slow_callback_duration, which defaults to 0.1 seconds. The message names the task and coroutine involved, which makes stalls like the one above easy to find.
Edge cases worth knowing
- Fairness is per iteration, not per priority. The ready queue has no priorities. A task that suspends and resumes every iteration gets the same share as any other.
- A forgotten
awaitnever runs. Callingworker()withoutawaitorcreate_taskonly creates a coroutine object. The loop never sees it. Python warns "coroutine ... was never awaited" when the object is garbage collected. - One loop per thread. A thread can run only one loop at a time. Calling
asyncio.runfrom inside a running loop raisesRuntimeError. - Thread safety. Loop methods like
call_soonare not thread-safe. From another thread, useloop.call_soon_threadsafe, which also wakes the selector.
Summary of the mental model
| Question | Answer |
|---|---|
| Who decides when a task runs? | The loop, from its ready queue |
| When can a task be interrupted? | Only at an `await` that suspends |
| What wakes a suspended task? | A future completing, via a ready-queue callback |
| What does `sleep(n)` guarantee? | Resume no earlier than n seconds |
| What happens during a blocking call? | Nothing else runs |
Exercise
A program runs two tasks. Task 1 prints "tick" every 0.5 seconds using await asyncio.sleep(0.5). Task 2 calls time.sleep(2) once, then returns. Both start at the same time. How many ticks print during those 2 seconds, and why? What changes if Task 2 uses await asyncio.sleep(2) instead?
Show answer
If Task 1 runs first, it prints one tick, suspends, and then Task 2 blocks the thread for 2 seconds, so no further ticks print until it returns. If Task 2 runs first, no tick prints during the 2 seconds. In both cases the timer for Task 1 comes due but cannot run, because the loop is not iterating while time.sleep holds the thread. With await asyncio.sleep(2), Task 2 suspends and the loop keeps polling, so Task 1 prints ticks at about 0, 0.5, 1.0, and 1.5 seconds.