Sub topic 5
Running coroutines concurrently as tasks
This chapter assumes you can write a coroutine with async def and await, and start a program with asyncio.run. It also assumes you know the event loop runs one piece of work at a time and switches only at await points.
Why awaiting is not enough
Awaiting a coroutine runs it to completion before the next line runs. Two awaits in a row therefore run one after the other, even though they are asynchronous.
import asyncio
import time
async def fetch(n):
await asyncio.sleep(1)
return n * 2
async def main():
start = time.perf_counter()
a = await fetch(1)
b = await fetch(2)
print(a, b, f"{time.perf_counter() - start:.1f}s")
asyncio.run(main())This prints 2 4 2.0s. The second call does not start until the first one returns. To overlap the waits, you need to hand the coroutines to the event loop as tasks.
What a task is
A task is a wrapper that schedules a coroutine on the event loop. asyncio.create_task(coro) creates the task and returns it right away. The coroutine starts running the next time the current code reaches an await and yields control.
import asyncio
import time
async def fetch(n):
await asyncio.sleep(1)
return n * 2
async def main():
start = time.perf_counter()
t1 = asyncio.create_task(fetch(1))
t2 = asyncio.create_task(fetch(2))
print("tasks created")
a = await t1
b = await t2
print(a, b, f"{time.perf_counter() - start:.1f}s")
asyncio.run(main())This prints tasks created, then 2 4 1.0s. Both sleeps run at the same time, so the total is about one second.
Working with a task
A task is also an awaitable object with a few useful methods.
| Method | What it does |
|---|---|
| `await task` | Waits for the task and returns its result, or raises its exception |
| `task.done()` | Returns `True` once the task has finished, failed, or been cancelled |
| `task.result()` | Returns the result of a finished task. It raises if the task failed or is not done yet |
| `task.cancel()` | Requests cancellation, which later raises `CancelledError` inside the task |
Awaiting a task more than once is safe. The result is stored, so later awaits return it immediately.
Common errors
Forgetting to keep a reference. The event loop holds only a weak reference to a task. If you discard the return value of create_task, the task can be garbage collected before it finishes. Store tasks in a variable or a collection.
import asyncio
background = set()
async def job():
await asyncio.sleep(0.1)
print("job finished")
async def main():
task = asyncio.create_task(job())
background.add(task)
task.add_done_callback(background.discard)
await asyncio.sleep(0.2)
asyncio.run(main())Never awaiting a failed task. If a task raises and nobody awaits it, the exception is only logged when the task is destroyed, with a message such as Task exception was never retrieved. Await every task you create, or collect them with gather or a TaskGroup, which the next chapters cover.
Calling create_task with no running loop. It raises RuntimeError: no running event loop when called from plain synchronous code. Call it from inside a coroutine started by asyncio.run.
Creating a task and never yielding. A task does not start until the creating coroutine reaches an await. If main finishes right after create_task, asyncio.run cancels the unfinished task during shutdown.
Exercise
A program runs t = asyncio.create_task(work()) and then return with no further awaits inside main. Why does work() usually never finish, and what is the smallest fix?
Show answer
The task only starts when main yields to the event loop, and asyncio.run cancels leftover tasks when main returns. The fix is to await t before returning, which both lets the task run and waits for its result.
Exercise
Given async def fetch(n) that sleeps one second, rewrite a = await fetch(1); b = await fetch(2) so both calls overlap using create_task. About how long does it take?
Show answer
Write t1 = asyncio.create_task(fetch(1)), t2 = asyncio.create_task(fetch(2)), then a = await t1 and b = await t2. It takes about one second instead of two.