Sub topic 2
How the event loop schedules work
This chapter assumes you know what a coroutine is at the level of async def and await syntax, and that you can tell I/O-bound work from CPU-bound work. Here you will see how one thread runs many coroutines.
The loop is a scheduler on one thread
An event loop is an object that runs a cycle on a single thread. It picks a task that is ready, runs it until it hits an await that cannot finish yet, then picks the next ready task. Nothing runs in parallel. Tasks take turns.
This is called cooperative scheduling. The loop never interrupts a task. A task gives up control only when it awaits something that is not ready.
What one cycle does
Each pass through the loop does roughly the following:
- Move timers that have expired into the ready queue.
- Ask the operating system which sockets or files are ready, using a selector such as
epoll, and queue the callbacks waiting on them. - Run every callback in the ready queue once. Each one resumes a task, which runs until its next suspension point.
- Repeat.
Seeing the interleaving
The loop switches tasks at each await that suspends. Run this example and compare the output with the delays.
import asyncio
async def worker(name, delay):
for step in range(2):
print(f"{name} step {step}")
await asyncio.sleep(delay)
async def main():
await asyncio.gather(worker("A", 0.2), worker("B", 0.1))
asyncio.run(main())The output is:
A step 0
B step 0
B step 1
A step 1Both workers start at time 0. Each prints its first line, then suspends in asyncio.sleep. The loop has no ready task, so it waits for the earliest timer. B's timer expires at 0.1 seconds, so B prints B step 1 first. A prints A step 1 at 0.2 seconds. The program finishes in about 0.3 seconds, not the 0.6 seconds that running the workers one after another would take.
What an await really does
When a coroutine awaits something that is not finished, such as a sleep, a socket read, or another task, the coroutine suspends. The awaited object registers a wake-up with the loop, either a timer or an I/O callback. The loop then runs something else.
An await on a coroutine that finishes without suspending does not return control to the loop. Awaiting a plain coroutine runs it directly inside the caller. Only awaiting something that actually waits gives other tasks a turn.
Why ordering is not guaranteed by you
The loop decides the order in which ready tasks run, and that order depends on timers and on when the OS reports I/O. Do not write code that relies on one task running before another unless you enforce the order with await, an Event, or a similar tool. Later chapters cover these.
The cooperative model has one useful property. Between two await points, your code runs without being interrupted by other tasks. Updating a plain variable there needs no lock.
Common errors at this level
- Calling a blocking function inside a coroutine, which freezes all concurrency.
- Expecting
await some_coroutine()to run other tasks. It runs only the coroutine you awaited, until that coroutine suspends. - Assuming a fixed order between tasks that are ready at the same time.
Exercise
A coroutine contains time.sleep(2) while three other tasks are waiting on asyncio.sleep(0.5). Why do the three tasks wake late, and what should replace time.sleep?
Show answer
time.sleep blocks the only thread, so the loop cannot run timers or resume tasks for 2 seconds. The three tasks resume only after it returns. Replace it with await asyncio.sleep(2), which suspends the coroutine and lets the loop run other tasks.