Business framing: Async programming lets services handle many IO-bound tasks (requests, DB calls, websockets) efficiently. This notebook introduces asyncio fundamentals, a Pyodide-safe event-loop demo, when to choose async vs threads, and safe patterns for idempotency and cancellation.
Learning objectives¶
Understand event loop, coroutine, task, and await.
Compare async (single-threaded concurrency) vs thread pools for IO-bound work.
Write simple asyncio code that is deterministic and safe to run in-browser.
Pyodide-safe asyncio demo (deterministic)¶
Visual intuition: event loop vs thread pool¶
Caption: Async uses a single event loop to multiplex coroutines; threads use OS threads for parallel blocking IO.
MCQ¶
Q: For a high-concurrency web client that performs many short HTTP requests, which model usually gives the best throughput with lowest overhead?
A) Multiprocessing
B) Thread pool
C) Asyncio
(Answer: C)
Exercises¶
Modify
simulated_ioto sometimes raise a recoverable exception; add a retry wrapper usingasyncio.sleepbetween retries.Implement a simple cancellation test: start a long-running coroutine and cancel it after a short timeout, observing cleanup behavior.
(Stretch) Compare
asynciovsThreadPoolExecutoron a simulated blocking function by measuring elapsed time for N tasks.