Sub topic 5
Running coroutines concurrently as tasks
This chapter assumes you can write a coroutine with async def and await, and start one with asyncio.run. It also assumes you know that the event loop runs one piece of code at a time on a single thread.
Why awaiting a coroutine is not enough
Awaiting a coroutine runs it to completion before the next line executes. The event loop can run other work while the coroutine is suspended, but only if other work has been scheduled. If main awaits one coroutine and then another, nothing else is scheduled, so the two run back to back.
A task is an object that wraps a coroutine and registers it with the event loop. Once a coroutine is a task, the loop drives it on its own. Your code can keep going, start more tasks, and collect the results later.
import asyncio
import time
async def fetch(name, delay):
await asyncio.sleep(delay)
return name
async def main():
start = time.perf_counter()
await fetch("a", 1)
await fetch("b", 1)
print(f"sequential: {time.perf_counter() - start:.1f}s")
start = time.perf_counter()
task_a = asyncio.create_task(fetch("a", 1))
task_b = asyncio.create_task(fetch("b", 1))
await task_a
await task_b
print(f"concurrent: {time.perf_counter() - start:.1f}s")
asyncio.run(main())This prints about 2.0s for the sequential version and about 1.0s for the concurrent one. Both tasks sleep during the same second.
| Form | What it does | Runs concurrently with other work? |
|---|---|---|
| `await coro()` | Runs the coroutine inline and waits for it | No, not unless other tasks already exist |
| `asyncio.create_task(coro())` | Schedules the coroutine and returns a `Task` immediately | Yes |
| `await task` | Waits for an already scheduled task and returns its result | Yes, the task was already running |
What create_task does
asyncio.create_task(coro, name=None) wraps the coroutine in a Task, schedules it on the running loop, and returns the Task right away. It needs a running loop, so call it from inside a coroutine or from a callback. Calling it from plain synchronous code raises RuntimeError: no running event loop.
The new task does not run at the moment of the call. The loop starts it the next time the current task gives up control, which happens at an await that actually suspends.
import asyncio
async def child():
print("child runs")
async def main():
task = asyncio.create_task(child())
print("task created")
await asyncio.sleep(0)
print("after sleep(0)")
await task
asyncio.run(main())The output is:
task created
child runs
after sleep(0)asyncio.sleep(0) suspends the current task for one loop iteration without waiting for any time to pass. That gives child its first turn. If main ran a long stretch of code without awaiting, child would never start, which is the cooperative scheduling you met earlier.
The life of a task
A task moves through a small set of states. It is pending until it finishes, and a pending task alternates between running and suspended. Only one task is running at any moment.
The Scheduled, Running, and Suspended states are all reported as "not done". The three end states are all reported as done().
Inspecting a task
A Task has a small API for checking where it stands:
task.done()is true once the task has returned, raised, or been cancelled.task.result()returns the value, or re-raises the task's exception. It raisesInvalidStateErrorif the task is not done yet.task.exception()returns the exception, orNoneon success.task.cancelled()is true if the task ended by cancellation.task.get_name()returns the name given at creation. Names make logs and error messages readable.task.add_done_callback(fn)callsfn(task)when the task finishes.
Check cancelled() before calling exception() or result(). A cancelled task raises CancelledError from both of them.
import asyncio
async def compute(n):
await asyncio.sleep(0.1)
if n == 3:
raise ValueError("three is unlucky")
return n * n
async def main():
tasks = [
asyncio.create_task(compute(n), name=f"compute-{n}")
for n in range(1, 5)
]
await asyncio.wait(tasks)
for t in tasks:
if t.cancelled():
print(t.get_name(), "cancelled")
elif t.exception() is not None:
print(t.get_name(), "failed:", t.exception())
else:
print(t.get_name(), "->", t.result())
asyncio.run(main())asyncio.wait waits until every task is done and does not raise task exceptions. Here the failure of compute-3 stays inside its task until we look at it. The other three tasks finish normally.
Where exceptions go
An exception inside a task does not propagate to the code that created it. The task stores it and finishes in the failed state. The exception reaches you only when you await the task, or call result() or exception().
If a failed task is garbage collected and nobody ever retrieved its exception, asyncio logs Task exception was never retrieved at that point. This is a diagnostic, not error handling. Treat it as a sign that some task's result was dropped.
import asyncio
async def explode():
raise RuntimeError("lost in the background")
async def main():
task = asyncio.create_task(explode())
try:
await task
except RuntimeError as exc:
print("caught:", exc)
asyncio.run(main())Awaiting the task re-raises its exception at the await, so an ordinary try/except works there. Combining many tasks and their failures is the subject of the gather and TaskGroup chapters.
Keep a reference to your tasks
The event loop keeps only a weak reference to the tasks it runs. If you call create_task and throw away the result, the garbage collector may destroy the task before it finishes. The failure is intermittent and hard to reproduce, because it depends on when collection happens.
The fix is to hold a strong reference until the task is done. A module-level set with a done callback is the standard pattern for fire-and-forget work.
import asyncio
background_tasks = set()
def spawn(coro, name=None):
task = asyncio.create_task(coro, name=name)
background_tasks.add(task)
task.add_done_callback(background_tasks.discard)
return task
async def heartbeat():
for i in range(3):
print("beat", i)
await asyncio.sleep(0.1)
async def main():
spawn(heartbeat(), name="heartbeat")
await asyncio.sleep(0.5)
asyncio.run(main())The set holds each task while it is pending. The callback removes the task once it is done, so the set does not grow without bound.
Tasks that outlive their creator
A task is independent of the coroutine that created it. If main finishes while other tasks are still pending, asyncio.run cancels those tasks and waits for the cancellations to finish before it closes the loop. A task that has not had its first turn yet is cancelled before its body ever executes.
So fire-and-forget does not mean the work will complete. If the program must wait for background work, hold the tasks and await them before returning from main.
Common mistakes
- Creating a task and never yielding. Code after
create_taskthat runs a long computation with noawaitdelays the new task until the computation ends. - Awaiting immediately after each create.
await asyncio.create_task(f())inside a loop gives the same timing as a plainawait f(). Create all the tasks first, then await them. - Passing a coroutine function instead of a coroutine.
create_task(fetch)fails. You must call it:create_task(fetch(1)). - Reading
result()too early. On a task that is not done,result()raisesInvalidStateError. Await the task first. - Forgetting that an await in the middle can interleave. Between two awaits your task has exclusive use of the loop. Across an await, other tasks may change shared state.
Exercise
A coroutine main calls asyncio.create_task(child()), where child prints "child ran" as its first statement. main then immediately returns without awaiting anything, and the program was started with asyncio.run(main()). Does "child ran" print? Why?
Show answer
No. create_task only schedules the task, and it first runs when main suspends at an await. main returns without suspending, so asyncio.run cancels the still pending task before its first step. A task cancelled before it starts never executes its body.
Exercise
You write for url in urls: result = await asyncio.create_task(fetch(url)) and find it takes as long as fetching the URLs one at a time. Why, and how do you fix it?
Show answer
Each task is created and then awaited before the next one is created, so only one task exists at a time. Create all the tasks first, for example tasks = [asyncio.create_task(fetch(u)) for u in urls], and then await each one, or wait for all of them together.