Lesson · Async Python
Event Loop
90 min readEvent Loop
The event loop schedules ready callbacks and tasks while suspended operations wait. A single blocking call can stall every task on that loop, which is why non-blocking boundaries matter.
Learning goals
- Describe the loop's cycle: run a ready task, stop at a suspension point, wake the task when its timer or I/O completes.
- Explain why both "before" lines print before either "after" line in the gathered example.
- Tell a blocking call from a non-blocking one by asking whether the thread returns to the loop during the wait.
- Distinguish a task from a future and say which one application code normally creates.
- Predict how the completion order changes when the two
asyncio.sleepdelays are swapped.
Mental model
The loop never runs two tasks at once: on one thread it always knows which task is mid-step, and a task is suspended only at an await. A callback that computes for a long time without awaiting keeps the loop from reaching the next ready item, which is why a single blocking call can stall everything.
One thread, one step at a time
a task hands the thread back only at an await
Mental model
the same mechanism as a compact list
ready queue → run task → await → suspended → event ready → run again
Core idea
The event loop is a single-threaded scheduler: it runs one ready task until that task suspends or finishes, then picks the next runnable item. Timers and I/O completions wake suspended tasks, so an await is really a request to be resumed later, and anything that fails to return control promptly delays every task behind it.
Event loop mental model
The event loop repeatedly runs ready callbacks and tasks until they suspend, then reacts to timers and I/O readiness. It depends on cooperative code returning control promptly.
Tasks
A task wraps a coroutine and drives it on the running loop, one step at a time, until it completes, fails, or is cancelled. asyncio.gather and asyncio.create_task both produce tasks, and a task is also a future whose result or exception can be retrieved once it is done.
Futures
A future is a low-level awaitable placeholder for a value that something else will set later. Tasks are futures managed by the loop; most application code awaits tasks or futures rather than creating a bare future and setting its result by hand.
Scheduling
Scheduling means handing work to the loop so it runs on a later iteration, through call_soon, create_task, or gather. The coroutine does not start at the call itself; it starts when the loop's next pass reaches the scheduled item.
Non-blocking execution
Non-blocking execution means waiting in a way that returns the thread to the loop instead of freezing it. await asyncio.sleep(...) yields and lets other tasks run, while time.sleep(...) holds the thread and stalls every task on that loop.
Walkthrough
asyncio.gather(task("A", 0.2), task("B", 0.1))schedules both coroutines as tasks before either body runs; the call itself only registers them with the loop.- Each task runs until its first suspension point, so "A before await" and "B before await" print back to back: both reach
await asyncio.sleep(...)and give control back without waiting in between. - When each timer fires, the loop resumes the matching task: "B after await" appears first at about 0.1 seconds, then "A after await" at about 0.2.
- Predict before running: the four printed lines in order, which task finishes first, and what
await asyncio.gather(...)returns here.
Experiments to try
- Replace
gatherwith two direct awaits (await task("A", 0.2)thenawait task("B", 0.1)) and time both versions; explain the change in total wait. - Insert
time.sleep(0.2)at the top of one task and watch the other task's prints freeze until the blocking sleep ends. - Change
task("B", 0.1)totask("B", 0.2)and predict, then confirm, that the two "after" lines land almost together. - Print both task handles before gathering them and read the pending state from the reprs.
Playable lesson
Lab: Event-loop timeline
Plot runnable and suspended tasks over time. Insert a blocking call and show how it freezes progress on the loop.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Event-loop timeline
Tasks on one thread
starting up
Ready queue
A, B
a task here could run right now, if the loop were free
Pending timers
none
the loop sleeps on the earliest of these
Predict first
Two tasks are waiting to run on one loop thread. Can both be mid-execution at the same instant?
Two coroutine objects exist but nothing has run yet. `gather` turns them into tasks and puts both on the loop's ready queue; the loop thread itself has not started either body.
Common mistakes
- Assuming the argument order in
gatherfixes the print order: the order follows delays and scheduling, so lengthening onesleepreorders the output. - Mixing
time.sleepor a long CPU loop into a task: the loop runs on one thread, so a blocking call freezes timers and I/O for every other task. - Dropping the handle returned by
asyncio.create_task: nobody awaits the result, so a failure may pass silently and pending tasks are only reported on shutdown. - Trying to call
asyncio.runinside a coroutine: it raisesRuntimeErrorbecause a loop is already running.
Practice: Easy
- Run the worked example and list the four printed lines in order; next to each, mark whether the loop was running that task or waiting on a timer.
- Replace the
gathercall with two sequential awaits, run both versions, and compare the total elapsed time usingtime.perf_counter(). - Add a third task with
delay=0and record where its lines land relative to A and B; explain the position from the suspension points.
Practice: Medium
- Add a heartbeat coroutine that prints a tick six times at 0.05 second intervals and gather it with the other two tasks; then insert
time.sleep(0.15)into one task and identify which ticks are late. - Create the two tasks manually with
asyncio.create_task, keep both handles, gather them, and annotate when each body first runs. - Compare
await task("A", 0.2)insidemainwithasyncio.run(task("A", 0.2))at module level; explain which one needs a running loop and which one creates a new one.
Practice: Hard
- Build a timeline logger: prefix every print in both tasks with
time.perf_counter()and reconstruct the interleaving from the timestamps, naming each suspension and wake. - Set up a comparison where one task calls
time.sleep(0.2)and the other awaitsasyncio.sleep(0.05); predict which prints are late and explain the result from single-threaded scheduling. - Vary delays (0.0, 0.05, 0.1) across three gathered tasks, run the program several times, and write a rule that predicts completion order from the delays alone.
Lesson checklist
- I can describe what the loop does between two suspension points of a single task.
- I can explain why
task("B", 0.1)finishes beforetask("A", 0.2)undergather. - I can classify a call as blocking or non-blocking by asking whether the thread returns to the loop during it.
- I can distinguish a task from a future and say who normally sets a future's value.
Remember
The loop is a single-threaded scheduler that switches tasks only at suspension points; `gather` schedules its arguments and awaits the group, so tasks interleave as their timers fire. Non-blocking waits return the thread to the loop, and one blocking call anywhere in a task freezes every other task behind it.
Interview angles
What is the main purpose of **Event loop mental model**?+
The event loop repeatedly runs ready callbacks and tasks until they suspend, then reacts to timers and I/O readiness. It depends on cooperative code returning control promptly.
What should you pay attention to when using **Tasks**?+
A task wraps a coroutine and drives it on the running loop, one step at a time, until it completes, fails, or is cancelled. asyncio.gather and asyncio.create_task both produce tasks, and a task is also a future whose result or exception can be retrieved once it is done.
How does **Futures** fit into this lesson?+
A future is a low-level awaitable placeholder for a value that something else will set later. Tasks are futures managed by the loop; most application code awaits tasks or futures rather than creating a bare future and setting its result by hand.
Why can a single `time.sleep(0.2)` in one task freeze the prints of another task?+
The loop runs tasks on one thread and regains control only at suspension points. time.sleep holds the thread for its full duration, so no timer or I/O callback can run and every other task stays suspended until the blocking call returns.