arthrop0d

Brief articles on varied topics.

How Python asyncio Schedules Coroutines

pythonconcurrencysoftware engineering

Python’s asyncio event loop is a scheduler that runs coroutines, waits for operating-system I/O notifications, and resumes the right work when it can continue. It usually does this in one thread rather than creating a thread for every network request, timer, or other operation.

The problem asyncio solves

A program that handles many network connections spends much of its time waiting: for a socket to accept bytes, for a DNS lookup, or for a timer to expire. A straightforward design gives each operation its own thread and lets that thread block while waiting.

That approach is easy to reason about, but threads consume memory and require scheduling by the operating system. Large numbers of mostly-waiting operations can therefore become expensive. Sharing data between threads also introduces locks and race conditions.

asyncio uses cooperative concurrency instead. A task runs until it reaches an await that cannot finish immediately. It then gives control back to the event loop. The loop runs another ready task while the first one is waiting.

asyncio does not make blocking code asynchronous. It provides a way for code designed to pause at well-defined points to share one thread efficiently.

From coroutine to task

A function declared with async def produces a coroutine when called. A coroutine is an object representing work that can pause and later continue. Calling it does not run its body immediately.

The event loop runs a coroutine through a Task, an asyncio object that tracks the coroutine’s progress and arranges for it to be stepped again. asyncio.run() creates and manages an event loop for the top-level coroutine. asyncio.create_task() schedules additional work on the currently running loop.

import asyncio

async def report(name, delay):
    await asyncio.sleep(delay)
    print(name)

async def main():
    first = asyncio.create_task(report("first", 1))
    second = asyncio.create_task(report("second", 0.2))
    await first
    await second

asyncio.run(main())

Both tasks are scheduled, but there is normally only one Python thread running them. The first task pauses in asyncio.sleep(), allowing the second task to run. The loop later resumes the first task when its timer is due.

What happens at await

An await asks an awaitable object—such as a timer, a socket operation, or another task—to produce a result. If that result is already available, the coroutine can continue immediately. Otherwise, the current Task records what it is waiting for and suspends.

Suspending does not save a thread stack somewhere while a thread blocks. The Task keeps the coroutine’s state, including where execution should continue and the local variables needed there. Control returns to the event loop, which can run other ready callbacks and tasks.

When the awaited operation completes, the loop schedules the suspended Task to run again. The next step sends the result back into the coroutine, so the expression containing await produces its value. If the operation failed, the loop resumes the coroutine by raising the corresponding exception at that await instead.

This is why code can look sequential while many operations are in progress:

async def read greeting():
    reader, writer = await asyncio.open_connection("example.com", 80)
    writer.write(b"GET / HTTP/1.0\r\nHost: example.com\r\n\r\n")
    await writer.drain()
    line = await reader.readline()
    writer.close()
    await writer.wait_closed()
    return line

At open_connection, drain, and readline, the task may pause. The loop can use the same thread to serve other connections during each wait. (In real code, the function name would be read_greeting; the example’s spacing is intentionally not valid Python.)

How the loop finds work to resume

The event loop repeatedly performs a cycle roughly like this:

  1. Run callbacks and tasks that are ready now.
  2. Determine how long it can wait before the next timer is due.
  3. Ask the operating system which registered I/O sources are ready, waiting up to that time.
  4. Turn resulting I/O events and expired timers into callbacks for the next pass.
  5. Run those callbacks, which may resume Tasks.

For sockets, the loop registers interest in events such as “this socket can be read without blocking” or “this socket can accept more writes.” On Unix, asyncio commonly uses a selector backed by operating-system facilities such as epoll, kqueue, or poll. Windows uses platform-appropriate event mechanisms; the important idea is the same: the OS watches many handles and reports which ones need attention.

Readiness is not the data itself. It means an operation is expected not to block. The loop then performs the non-blocking read or write, and the asyncio protocol or stream code supplies the result to the waiting Task. If only part of a requested operation can proceed, the rest remains registered for a later notification.

Timers such as asyncio.sleep() do not require a thread to sleep. The loop records a deadline and includes that deadline when choosing how long to wait for I/O. When the deadline passes, it marks the timer’s callback ready.

Why one blocked task can still block everything

The event loop is cooperative: a running task must reach an await point before another task gets a turn. A long CPU loop, a synchronous database driver, time.sleep(), or a blocking file and network call can hold the event-loop thread and prevent it from checking I/O.

For blocking work, asyncio can explicitly submit a function to an executor, which uses worker threads or processes. That is an optional escape hatch, not what happens for every await.

The familiar messages coroutine was never awaited, Task was destroyed but it is pending, and Event loop is closed often point to mistakes in creating, scheduling, or shutting down this machinery. Understanding the loop’s central rule helps interpret them: tasks make progress only when the event loop can run them, and they yield only when their code actually awaits non-blocking work.

← All articles