Log inStart free
LESSON 1.11 · 6 STAGES · 2 CONTROLS · 3 CHECKSPRO · PREVIEW

The asyncio event loop

Watch one event loop run two coroutines on one thread, switching at each await.


Pro lesson. Stage 1 is free to watch. Pro opens all 6 stages, 2 controls and 3 checks, in this lesson and every other.

Go Pro · $8.25/mo
EXPLAINER · 1.11 · EVENT LOOP BAYT = 0 MS · TICK 0 · 1 READY · 0 TIMERS
01
Stage 1 of 6 · Make a coroutine
main() makes a coroutine and runs no line. asyncio.run wraps it in a task on a new event loop.
Explain it simply

Calling main doesn't run its code. It makes a coroutine, an object that holds a function call that hasn't started. asyncio.run then makes the event loop, the panel at the top, and wraps main in a task. The task's first step waits in the ready queue, like a ticket in a line.

The coroutine main has not started: CORO_CREATED at line 15. Task main holds it. The ready queue holds main's first step. The clock shows 0 ms.

frame, event loopcoroutine, task, Python workawait, timerI/O waitrunning code, outputblocked or late
programevent loopcall stacktasks and coroutinestimelineprintednot startedmade by asyncio.run; tick 1 runs the front stepreadytimers(none)1 wait for a timer2 due timers → ready3 run ready stepst = 0 msstep main<module>line 21Task mainpendingstep in the ready queuemain()line 150 ms20 ms40 ms60 ms80 ms100 ms120 msthreadmain1import asyncio, time2def ms(): return time.perf_counter() * 10003def work(n):4 end = ms() + n5 while ms() < end: pass7async def coro(name, wait):8 print(name, "starts")9 work(5)10 await asyncio.sleep(wait / 1000)11 work(5)12 print(name, "ends")13 return wait15async def main():16 a = asyncio.create_task(coro("I/O 1", 51))17 b = asyncio.create_task(coro("I/O 2", 43))18 print(await a, await b)20t0 = ms()21asyncio.run(main())22print(round(ms() - t0), "ms")mainprogramevent loopcall stacktasks and coroutinestimelineprintednot startedmade by asyncio.run; tick 1 runs the front stepreadytimers(none)1 wait for a timer2 due timers → ready3 run ready stepst = 0 msstep main<module>line 21Task mainpendingstep in the ready queuemain()line 150 ms20 ms40 ms60 ms80 ms100 ms120 msthreadmain1import asyncio, time2def ms(): return time.perf_counter() * 10003def work(n):4 end = ms() + n5 while ms() < end: pass7async def coro(name, wait):8 print(name, "starts")9 work(5)10 await asyncio.sleep(wait / 1000)11 work(5)12 print(name, "ends")13 return wait15async def main():16 a = asyncio.create_task(coro("I/O 1", 51))17 b = asyncio.create_task(coro("I/O 2", 43))18 print(await a, await b)20t0 = ms()21asyncio.run(main())22print(round(ms() - t0), "ms")main
Toy: I/O 1 and I/O 2 of the 1.C1 toy · 51 ms and 43 ms waits · 5 ms of Python each side · CPython 3.12
STAGE 1 / 6
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
main()⇒coroutine, 0 lines run\sy{main}{data}{\mathrm{main}()} \Rightarrow \sy{coro}{data}{\text{coroutine}},\ \text{0 lines run}
ready=[ step main ], t=0 ms, tick 0\mathrm{ready} = [\,\text{step main}\,],\ t = 0\ \text{ms},\ \text{tick } 0

A call to an async function makes a coroutine and runs nothing.

Common mix-ups

MYTHCalling an async function starts running it.

The fix, and 1 more mix-up with the diagram to show them, come with Pro.

Predict, then reveal
3 CHECKS · PRO
Q01With plain calls instead of create_task, how long does the run take?

Make your guess, then test it in the diagram. All 3 checks come with Pro.

PRO LESSON · YOU WATCHED STAGE 1 OF 6
Unlock the full explainer
  • 5 more stages and 2 live controls
  • 2 mix-up cards and 3 predict-then-reveal checks
  • Watch it as a narrated video, in three voices
  • Every Pro lesson and capstone · 656 in total

$99 a year, or $15 a month. Cancel any time.