Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 40 ยท Event Loop and Coroutines

How the asyncio Event Loop Works

Understand the asyncio event loop: the ready queue, timers, await points, asyncio.sleep(0), scheduling order and why one blocking call freezes everything.

The event loop is the heart of asyncio. It is a plain loop that repeatedly asks "what is ready to run right now?", runs it, and goes back to asking. Everything else in this course (tasks, timeouts, queues, network code) is built on that single idea. Once you can picture the loop, async behavior stops being mysterious, and you can predict the order in which things print.

The loop in pseudocode

Here is the idea, simplified:

TEXT
while there is work:
    run every callback in the ready queue (one at a time)
    move timers that have expired into the ready queue
    ask the operating system which sockets/files became ready
    move their callbacks into the ready queue

A callback is a small function the loop will call. When you await something, asyncio registers a callback that will resume your coroutine later, then returns to the loop. Each piece of your code between two awaits runs as one uninterrupted step. Between steps the loop can switch to someone else.

flowchart TD
    R["Ready queue<br/>callbacks to run now"] --> S["Run one step<br/>until the next await"]
    S --> T["Timers due?<br/>move to ready queue"]
    T --> I["I/O ready?<br/>move to ready queue"]
    I --> R

The loop never stops while there is work: run ready steps, collect finished timers and I/O, repeat.

Scheduling a plain callback

You can talk to the loop directly. loop.call_soon(func, *args) appends a callback to the ready queue, and loop.call_later(delay, func, *args) schedules one after a delay:

Python call_soon and call_later

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

main keeps running until it reaches its first await; only then does the loop get a turn and run the callbacks. The ready callback fires first, and the timers fire in order of their deadlines, not the order they were written.

Interleaving at await points

Two coroutines take turns only at awaits. await asyncio.sleep(0) is a special case: it yields to the loop for one turn and asks to be resumed immediately, which makes the switching visible without any real waiting:

Python Taking turns with sleep(0)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The output alternates A, B, A, B, and so on. Remove the await asyncio.sleep(0) line and each worker will run to completion before the other starts, because nothing ever hands control back to the loop. That is the whole rule of cooperative multitasking.

The scheduling order is deterministic

In a given loop, callbacks run in the order they were scheduled (first in, first out). Timers with the same deadline run in the order they were created. This is why simple examples print the same output every time. It does not mean you should rely on subtle ordering in production, but it makes asyncio programs much easier to reason about and test than thread programs.

Getting the loop and reading its clock

Inside a coroutine, call asyncio.get_running_loop(). It returns the loop that is running you, and raises RuntimeError if there is none. Avoid the older asyncio.get_event_loop() in new code.

The loop has its own monotonic clock, loop.time(), measured in seconds from an arbitrary starting point that never goes backwards. Timers use this clock, not the wall clock, so changing the system time cannot break them. loop.call_at(when, ...) takes an absolute loop.time() value and loop.call_later(delay, ...) a relative one:

Python The loop clock and timer handles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A TimerHandle can be cancelled before it fires. This is how asyncio.sleep and timeouts are built.

What await really does

When you write await asyncio.sleep(1), three things happen:

  1. sleep creates a future and asks the loop to complete it in one second (call_later).
  2. Your coroutine suspends, and the current step ends. The loop is free.
  3. When the timer fires, the future is completed, which schedules a callback that resumes your coroutine.

Every wait in asyncio follows this pattern: a future is created, something completes it later, and the completion resumes the waiting coroutine. Sockets, queues, locks and subprocess pipes all use it. You will meet futures directly in Futures and callbacks.

One loop, one thread

An event loop belongs to the thread that runs it. Only code on that thread may touch loop objects freely. That is why asyncio objects are not thread-safe; to call into a loop from another thread you must use loop.call_soon_threadsafe or asyncio.run_coroutine_threadsafe. Inside a single thread you can have only one running loop, which is why nesting asyncio.run fails in a normal program.

The price of a single thread is the lesson you saw in asyncio versus threads: a step that never reaches an await starves everyone. A step should be short, or it should hand its work elsewhere (blocking the loop).

Event loop policies and uvloop

CPython ships a default loop (selector-based on Linux and macOS, proactor-based on Windows). Third-party loops such as uvloop replace it with a faster implementation written in C and are installed through the same asyncio API. Your coroutines do not change. This course uses only the standard loop.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. At which points can the event loop switch from one coroutine to another?

    Switching is cooperative. A coroutine runs without interruption until it awaits something that is not ready.
  2. 2. What does await asyncio.sleep(0) do?

    It gives every other ready callback a turn, which is why it is used to let other tasks make progress.
  3. 3. Which clock do loop timers use?

    loop.time() never goes backwards, so timers are not disturbed by system clock changes.
  4. 4. Two callbacks are scheduled with call_soon, A then B. Which runs first?

    The ready queue is first in, first out.

Summary

  • The event loop repeatedly runs ready callbacks, then collects expired timers and ready I/O.
  • A coroutine runs in uninterrupted steps between awaits; the loop switches only at awaits.
  • call_soon, call_later and call_at schedule plain callbacks; loop.time() is the monotonic clock.
  • Every await is built from a future that something completes later.
  • One loop runs on one thread, so a step that never awaits blocks everything.

Next: Coroutines and awaitables