Skip to content

Asynchronous Python: asyncio

Beginning of the lesson

Asynchronous Python: asyncio

One thread, thousands of overlapping I/O operations, no callbacks

Big Idea: asyncio runs many I/O-bound operations concurrently on a single thread. A coroutine runs until it hits an await on something not yet ready (a socket, a timer, a response); at that point it suspends and hands control back to the event loop, which runs another ready coroutine. Nothing runs in parallel on the CPU — instead, waiting time is overlapped. This is cooperative concurrency: tasks yield voluntarily at every await.
By the end you will be able to:
  • explain the difference between concurrency and parallelism, and why asyncio targets I/O-bound work;
  • write async def coroutines and drive them with asyncio.run;
  • schedule real concurrency with asyncio.create_task and asyncio.gather;
  • bound work in time with asyncio.timeout and handle CancelledError correctly;
  • consume streams with async for and write async generators;
  • recognise the traps: forgotten await, blocking calls that freeze the loop, and CPU-bound misuse.

1. Concurrency is not parallelism

Parallelism means several things run at the same instant on different CPU cores (what multiprocessing gives you). Concurrency means several tasks are in progress and interleaved, but at any single instant only one is actually executing. asyncio provides concurrency, not parallelism: it uses one thread and overlaps the waiting.

This is exactly right for I/O-bound work — HTTP requests, database queries, reading files, talking to sockets — where your program spends most of its time waiting for something external. While one request waits for bytes to arrive, the loop runs another. For CPU-bound work (crunching numbers, parsing huge blobs) asyncio gives no speed-up at all, because there is no idle waiting to overlap; use processes or threads there instead.

Analogy: a single chef with many pots. A good chef does not stand watching one pot boil. They start the pasta, and while it boils they chop vegetables; when the oven timer rings they attend to it. One chef (one thread), many dishes in flight (many coroutines). The chef never cooks two dishes in the same instant, but total dinner time collapses because the waiting overlaps. asyncio is that chef; each await is a moment of "this needs time, let me do something else meanwhile".

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers