Sub topic 2
Running work concurrently with create_task
This chapter assumes you have Python 3.11 or newer and can write coroutine functions with async and await. It also assumes you can start a program with asyncio.run. By the end you will know how asyncio.create_task starts work in the background and how to collect results correctly.
Why await alone runs work one step at a time
Awaiting a coroutine runs it to completion before the next line executes. Two awaits in a row therefore run one after the other, even though the event loop could have used the waiting time.
asyncio.create_task(coro) wraps a coroutine in a Task and schedules it on the running event loop. It returns the Task immediately. The loop then runs the task whenever the current code reaches an await and yields control.
import asyncio
import time
async def fetch(name, delay):
await asyncio.sleep(delay)
return f"{name} done"
async def sequential():
start = time.perf_counter()
a = await fetch("a", 0.2)
b = await fetch("b", 0.2)
print(a, b, f"{time.perf_counter() - start:.1f}s")
async def concurrent():
start = time.perf_counter()
t1 = asyncio.create_task(fetch("a", 0.2))
t2 = asyncio.create_task(fetch("b", 0.2))
a = await t1
b = await t2
print(a, b, f"{time.perf_counter() - start:.1f}s")
asyncio.run(sequential())
asyncio.run(concurrent())The first version takes about 0.4 seconds and the second about 0.2 seconds. In the second version both sleeps overlap.
What happens when you call create_task
Calling create_task does not run any of the coroutine's code. It only registers the task. The task starts at the next point where the calling code yields to the loop. In the example above, that point is await t1.
A task is a unit of scheduling. A coroutine is only the code. The same coroutine function can back many tasks, and each task has its own state, result, and exception.
Reading results and errors
Awaiting a task returns its result, or raises the exception the task ended with. If you never await a task and it fails, Python only logs "Task exception was never retrieved" when the task is garbage collected. Always await tasks you care about, or collect them in a structure that does.
import asyncio
async def square(n):
await asyncio.sleep(0.1)
return n * n
async def main():
tasks = [asyncio.create_task(square(n)) for n in range(5)]
results = [await t for t in tasks]
print(results)
asyncio.run(main())This prints [0, 1, 4, 9, 16]. All five tasks are created before the first await, so they run together. Awaiting them in creation order keeps the results in order.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Writing `await create_task(c)` immediately for each task | No speed-up, because each task finishes before the next is created | Create all tasks first, then await them |
| Passing the function instead of a coroutine, `create_task(fetch)` | `TypeError: a coroutine was expected` | Call it: `create_task(fetch("a", 0.2))` |
| Calling `create_task` with no running loop | `RuntimeError: no running event loop` | Call it from inside a coroutine started by `asyncio.run` |
| Running blocking code such as `time.sleep` in a task | Every task stalls, because the loop is blocked | Use `await asyncio.sleep`, or move the blocking work to a thread |
Exercise
You write a = await asyncio.create_task(fetch("a", 1)) followed by b = await asyncio.create_task(fetch("b", 1)). How long does this take, and how would you change it so both fetches overlap?
Show answer
It takes about 2 seconds. Each task is created and awaited to completion before the next one exists. Create both tasks first (t1 = create_task(...), t2 = create_task(...)), then await t1 and t2. The total is then about 1 second.