Sub topic 1
Coroutines, tasks, and the event loop in brief
Prerequisites
This chapter assumes you have the following:
- Python 3.11 or newer installed.
- Comfort with
async/awaitsyntax and with defining coroutine functions. - Familiarity with
try/except/finally, and withwithandasync with. - Basic experience running code through
asyncio.run.
The working model
Three objects do the work in asyncio, and later chapters on task groups, timeouts, and cancellation all build on them.
- A coroutine is the object you get by calling an
async deffunction. Calling it does not run any of its body. It only creates a paused computation. - A task wraps a coroutine and schedules it on the event loop. The task is what actually runs, and it records the result or exception.
- The event loop is a scheduler that runs on one thread. It runs one task at a time, and a task keeps control until it reaches an
awaitthat cannot finish immediately.
The key point is that asyncio uses cooperative scheduling. A task gives control back to the loop only at an await. Other tasks make progress only while the current task is suspended.
A coroutine alone does nothing
Awaiting a coroutine directly runs it to completion before the next line executes. Nothing else runs concurrently with it from your code's point of view.
import asyncio
import time
async def fetch(name, delay):
await asyncio.sleep(delay)
return f"{name} done"
async def main():
start = time.perf_counter()
print(await fetch("a", 0.2))
print(await fetch("b", 0.1))
print(f"sequential: {time.perf_counter() - start:.1f}s")
start = time.perf_counter()
t1 = asyncio.create_task(fetch("a", 0.2))
t2 = asyncio.create_task(fetch("b", 0.1))
print(await t1)
print(await t2)
print(f"concurrent: {time.perf_counter() - start:.1f}s")
asyncio.run(main())The sequential part takes about 0.3 seconds because each await finishes before the next begins. The concurrent part takes about 0.2 seconds. create_task schedules both coroutines right away, so their sleeps overlap.
Here is what asyncio.run does. It creates an event loop, runs main() as the first task, and closes the loop when main() returns.
Common errors
These mistakes come up often in the first week with asyncio.
- Forgetting
await. Callingfetch("a", 0.2)withoutawaitgives you a coroutine object. Python warnscoroutine 'fetch' was never awaited, and the body never runs. - Blocking the loop. A call such as
time.sleep(1)or a heavy CPU loop inside a coroutine never reaches anawait. Every other task stalls until it returns. Useawait asyncio.sleep(1), or move blocking work to a thread withasyncio.to_thread. - Assuming
create_taskwaits. It returns immediately. The task starts running only when the current task next suspends. - Expecting parallelism. Tasks interleave on one thread. They overlap waiting time, not computation.
Where this leads
The next chapters cover create_task in detail, then TaskGroup, asyncio.timeout, and cancellation. Each is a way to control tasks that the loop is already running.
Exercise
In the example above, why does the concurrent section take about 0.2 seconds rather than 0.3 seconds?
Show answer
create_task schedules both coroutines on the event loop before either is awaited. When the first task reaches await asyncio.sleep, the loop runs the second one, so the two sleeps overlap. The total time is the longest sleep (0.2 s), not the sum of both.
Exercise
A coroutine calls time.sleep(2) while three other tasks are waiting on network responses. What happens to those three tasks, and what is the fix?
Show answer
They are stalled for the full 2 seconds, because time.sleep never returns control to the event loop. Replace it with await asyncio.sleep(2), or run the blocking call with await asyncio.to_thread(...).