Advanced Python: asyncio, concurrency, and non-blocking I/O
The event loop, async and await, Task, gather, and sleep; how this differs from threads; GIL limits on CPU work; and 20 exercises with solutions.
Getting started
Home Assistant
Buying
The event loop, async and await, Task, gather, and sleep; how this differs from threads; GIL limits on CPU work; and 20 exercises with solutions.


AI-generated illustration
Some links on this page are affiliate links. The button opens Amazon so you can check today’s price.
The asyncio module gives you an event loop that runs coroutines: functions declared with async def and called with await. Unlike operating-system threads, coroutines are cooperative. They yield control at await points, which suits I/O (the network, and disk access through async libraries) and concurrency across many connections without creating thousands of threads.
Important: asyncio does not parallelize pure CPU work across several cores. The GIL still applies. For parallel CPU work, see multiprocessing or concurrent.futures.ProcessPoolExecutor.
import asyncio
async def main():
print("start")
await asyncio.sleep(0.1)
print("end")
asyncio.run(main())
asyncio.run creates the loop, runs main() to completion, and shuts it down cleanly.
gatherasyncio.create_task(coro) schedules a coroutine as a concurrent Task. await asyncio.gather(a(), b()) starts several coroutines and waits until all of them finish (exceptions are collected).
Calling a blocking function (time.sleep, a heavy calculation) inside a coroutine blocks the whole loop: the other tasks do not run. Use await asyncio.sleep, or loop.run_in_executor to hand the work to the thread pool.
Exercise 1 — A minimal program with asyncio.run(hello()), where hello does await asyncio.sleep(0) and then print("ok"). Easy
import asyncioasync def hello(): await asyncio.sleep(0) print(“ok”)
asyncio.run(hello())
Exercise 2 — await asyncio.gather(sleep(0.1), sleep(0.1)) and check that the total time is < 0.2 s (order of magnitude). Easy
import asyncio, time
async def main():
t0 = time.perf_counter()
await asyncio.gather(asyncio.sleep(0.1), asyncio.sleep(0.1))
print(time.perf_counter() - t0)
asyncio.run(main())
Exercise 3 — Use asyncio.create_task on a coroutine that counts to 3, with await sleep(0) between each print. Easy
import asyncioasync def count(): for i in range(1, 4): await asyncio.sleep(0) print(i)
async def main(): t = asyncio.create_task(count()) await t
asyncio.run(main())
Exercise 4 — What is the difference between async def and a normal function that returns a coroutine? Easy
# async def defines a coroutine; calling it returns a coroutine object, which the loop runs.
Exercise 5 — Why is time.sleep(1) inside async def a bad idea? Easy
# It blocks the event-loop thread; every async task freezes.
Exercise 6 — Use asyncio.TimeoutError in concept with wait_for around a coroutine that sleeps too long. Easy
import asyncioasync def lent(): await asyncio.sleep(10)
async def main(): try: await asyncio.wait_for(lent(), timeout=0.05) except asyncio.TimeoutError: print(“timeout”)
asyncio.run(main())
Exercise 7 — What does asyncio.run do, compared with loop.run_until_complete, from a user’s point of view? Easy
# run is the recommended high-level API: it creates the loop and closes it cleanly.
Exercise 8 — asyncio.Semaphore(2) to cap simulated concurrent calls at 2. Intermediate
import asyncioasync def work(i, sem): async with sem: print(“start”, i) await asyncio.sleep(0.05) print(“end”, i)
async def main(): sem = asyncio.Semaphore(2) await asyncio.gather(*(work(i, sem) for i in range(5)))
asyncio.run(main())
Exercise 9 — asyncio.Queue: a producer that puts, and a consumer that gets. Intermediate
import asyncioasync def prod(q): await q.put(1) await q.put(2)
async def cons(q): print(await q.get()) print(await q.get())
async def main(): q = asyncio.Queue() await asyncio.gather(prod(q), cons(q))
asyncio.run(main())
Exercise 10 — return_exceptions=True in gather: what happens. Intermediate
# Exceptions become return values instead of propagating.
Exercise 11 — Start a minimal TCP asyncio.Server (read the docs) — a sketch. Intermediate
# async def handle(reader, writer): ... ; asyncio.start_server(handle, host, port); serve forever.
Exercise 12 — asyncio.shield: what is it for? Intermediate
# Protects a task from cascading cancellation; cancellation does not propagate directly.
Exercise 13 — run_in_executor to call a blocking requests.get — a sketch. Intermediate
# loop = asyncio.get_running_loop(); await loop.run_in_executor(None, requests.get, url)
Exercise 14 — The difference between concurrency and parallelism, in one sentence. Intermediate
# Concurrency: interleaving. Parallelism: simultaneous execution on several cores.
Exercise 15 — A producer/consumer pattern with a Queue and a sentinel to stop. Hard
# Put None at the end; the consumer breaks on None.
Exercise 16 — asyncio.CancelledError: when is it raised? Hard
# When the task is cancelled with task.cancel().
Exercise 17 — Why is asyncio.get_event_loop() outside an async context discouraged in 3.10+? Hard
# Prefer get_running_loop() inside a coroutine so you do not pick an ambiguous loop.
Exercise 18 — asyncio.TaskGroup (3.11+): the advantage over gather. Hard
# Structured handling of child tasks and cascading cancellation (async with syntax).
Exercise 19 — Measure wall time versus CPU time for a coroutine that mostly sleeps. Which one reflects I/O wait? Hard
# Wall time (time.perf_counter) goes up; CPU time barely moves because there is little CPU work.
Exercise 20 — When would you choose anyio or trio over asyncio alone? (a short answer). Hard
# Third-party libraries for a unified API, structured timeouts, and nursery patterns, depending on the ecosystem.
Advanced static typing: Protocol, generics, Literal.
Check today’s price on Amazon (Python asyncio)
Was this page helpful?
Thank you!
What should we improve?
Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.
Cookies and analytics
We use Google Analytics 4 to understand how the site is used (page views, navigation). It is only switched on if you accept. Declining does not stop you using the site. More: cookie settings and privacy policy (in French).