How does asyncio's event loop schedule and switch between multiple coroutines, and what makes this cooperative rather than preemptive?
Short answer
The event loop maintains a queue of ready-to-run tasks; a coroutine voluntarily YIELDS control back to the loop only at an 'await' point (specifically when awaiting something not yet complete) — this is COOPERATIVE multitasking, since a coroutine that never awaits can block the…
Advertisement
AModel answer
The event loop maintains a queue of ready-to-run tasks; a coroutine voluntarily YIELDS control back to the loop only at an 'await' point (specifically when awaiting something not yet complete) — this is COOPERATIVE multitasking, since a coroutine that never awaits can block the entire event loop, unlike preemptive OS thread scheduling which can interrupt a thread at any instruction.
async def hog_the_loop():
total = 0
for i in range(100_000_000): # no await inside -- blocks the ENTIRE event loop
total += i
return total
# Every other coroutine is frozen until this finishes, since it never yields controlReal-world example
Understanding why a synchronous, CPU-heavy computation accidentally placed inside an async function can freeze an entire asyncio application.
Likely follow-ups
- How would you fix a CPU-bound blocking operation inside an async function without freezing the whole event loop?
Related topics