Sub topic 1
Why asyncio: Concurrency for I/O-Bound Programs
Prerequisites
This chapter assumes you know Python functions, exceptions, context managers, generators, and the difference between I/O-bound and CPU-bound work.
Why asyncio?
Concurrency means making progress on several tasks during the same period. An I/O-bound task spends much of its time waiting for a file, database, network response, or timer. While one task waits, another task can use the available time.
asyncio provides concurrency on a single thread. It does not make CPU-heavy calculations run in parallel. For CPU-bound work, consider processes or native libraries that release Python's interpreter lock.
How the Event Loop Schedules Work
The event loop is a scheduler that runs ready asynchronous tasks. A coroutine runs until it reaches await. At that point, it pauses and gives control back to the event loop. The loop can then run another coroutine whose work is ready.
This is called cooperative scheduling because each coroutine must reach an await willingly. A blocking call, such as time.sleep(5), prevents the event loop from running anything else during those five seconds.
Writing Coroutines with `async def` and `await`
A function declared with async def is a coroutine function. Calling it creates a coroutine object; it does not run the function immediately. Use await inside another coroutine to run it and wait for its result.
import asyncio
async def greet(name, delay):
await asyncio.sleep(delay)
return f"Hello, {name}"
async def main():
message = await greet("Ada", 0.1)
print(message)
asyncio.run(main())asyncio.sleep pauses without blocking the thread. During the pause, the event loop can schedule other work.
Starting Your Program with `asyncio.run`
asyncio.run(main()) creates an event loop, runs the top-level coroutine, and closes the loop when it finishes. It is the usual entry point for a standalone asynchronous script.
Do not repeatedly call asyncio.run inside an already-running event loop. In environments such as some notebooks and asynchronous web servers, the environment usually provides the loop, so await the coroutine there instead.
Exercise
Why does await asyncio.sleep(1) allow other asynchronous work to run, while time.sleep(1) does not?
Show answer
The asynchronous sleep yields control to the event loop. The blocking sleep holds the thread and stops the event loop from scheduling other tasks.