Async tasks and cancellation
Async code lets one task yield while it waits so another task can make progress.
How it works
In the example, each label task reaches sleep and gives the event loop a turn. Both waits can be active at once. Completion order can differ, but gather returns results in the order the coroutines were passed. A CPU-heavy calculation still occupies the thread unless you move it elsewhere.
Walk through an example
An async function returns a coroutine. An event loop can schedule coroutines that pause at await, which is useful when several operations spend time waiting for input or output.
What to watch for
A blocking call inside an async function can still freeze the event loop. Use an async library for blocking I/O patterns or move blocking work out of the event loop.
Code example
import asyncio
async def label(name):
await asyncio.sleep(0.01)
return name
async def main():
print(await asyncio.gather(label("A"), label("B")))
asyncio.run(main())Check your understanding
Can the timer waits overlap?
See the example and explanation
- Worked example
- Given
Two tasks each await a one-second timer and are started together. - Answer
Yes.
Each task gives control back to the event loop while it waits, so the other task can wait during the same time.