Sub topic 2
Running work concurrently with create_task
This chapter assumes you know async/await syntax, can write coroutine functions, and can start a program with asyncio.run. It also assumes you are on Python 3.11 or newer. You will learn how asyncio.create_task turns a coroutine into concurrent work, when that work starts, and how results and errors get back to your code.
Coroutines do nothing until something drives them
Calling an async def function does not run its body. It returns a coroutine object, which is a paused function call. Something has to drive it. There are two ways to do that:
await cororuns the coroutine to completion before the next line of your code runs.asyncio.create_task(coro)wraps the coroutine in aTaskand schedules it on the event loop. Your code keeps going.
A Task is the event loop's handle on a running coroutine. It holds the coroutine's state, its result or exception, and its cancellation status. Many tasks can be in progress at once, but only one runs at any instant. Each task runs until it hits an await that cannot finish immediately. Then it hands control back to the loop.
Sequential versus concurrent
Awaiting coroutines one after another adds their durations. Wrapping them in tasks lets their waiting overlap.
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")
async def main():
await sequential()
await concurrent()
asyncio.run(main())The output is:
a done b done 0.4s
a done b done 0.2sIn concurrent, both tasks are scheduled before the first await. While task a sleeps, the loop runs task b, so the two sleeps overlap.
When does a task actually start?
create_task only schedules the task. The task's first step runs the next time the creating code yields to the loop. That happens at an await that suspends, or at await asyncio.sleep(0), which yields without waiting.
import asyncio
async def show(label):
print(f"{label}: started")
await asyncio.sleep(0)
print(f"{label}: finished")
async def main():
task = asyncio.create_task(show("task"))
print("main: task created")
await asyncio.sleep(0)
print("main: after first yield")
await task
asyncio.run(main())The output is:
main: task created
task: started
main: after first yield
task: finishedThe task does not run at the moment of creation. It starts only when main yields. Each sleep(0) hands control to whichever task is next in the loop's ready queue, so the two coroutines take turns.
This ordering matters when you write code that depends on a task having begun. Do not assume the task has started, or finished any setup, just because create_task returned.
Getting results and errors back
A Task is awaitable. Awaiting it suspends your coroutine until the task finishes. It then returns the task's return value, or re-raises the exception the task ended with.
import asyncio
async def boom():
await asyncio.sleep(0.1)
raise RuntimeError("boom")
async def main():
task = asyncio.create_task(boom(), name="boom-task")
try:
await task
except RuntimeError as exc:
print("caught:", exc, task.get_name(), task.done())
asyncio.run(main())This prints caught: boom boom-task True. A task's exception does not interrupt the code that created it. It is stored on the task and surfaces only when something awaits the task or asks for its outcome.
You can inspect a task without awaiting it:
| Method | Meaning |
|---|---|
| `task.done()` | `True` once the task finished, failed, or was cancelled |
| `task.result()` | Returns the value, or raises the task's exception. Raises `InvalidStateError` if the task is not done |
| `task.exception()` | Returns the exception, or `None` if the task succeeded. Raises `InvalidStateError` if not done |
| `task.cancelled()` | `True` if the task ended by cancellation |
| `task.get_name()` | The name passed with `name=`, or a generated one such as `Task-3` |
Giving tasks a name costs nothing. It makes log lines and the repr of a task far easier to read when something goes wrong.
Arguments, context, and the running loop
create_task takes a coroutine object, not a function. Pass fetch("a", 0.2), not fetch. Passing the function raises TypeError: a coroutine was expected.
create_task also needs a running event loop in the current thread. Calling it from plain synchronous code, outside asyncio.run or a coroutine, raises RuntimeError: no running event loop. When this happens, the coroutine object you built is never awaited, so you will also see a warning about that.
Each task runs in a copy of the contextvars context that was current when you created it. Changes the task makes to a context variable do not leak back to the creator, and later changes by the creator do not reach the task. This is how request-scoped values like trace IDs flow into child tasks safely.
Common mistakes
| Symptom | Cause | Fix |
|---|---|---|
| `RuntimeWarning: coroutine 'x' was never awaited` | Called `x()` without `await` or `create_task` | Await it, or wrap it in a task |
| No speedup from tasks | Awaited each task right after creating it | Create all tasks first, then await them |
| Whole program freezes during a task | Blocking call such as `time.sleep` or a synchronous HTTP client | Use an async API, or move the call to `asyncio.to_thread` |
| `Task exception was never retrieved` logged at exit | A task failed and nobody awaited it | Await it, or attach handling for its outcome |
| `RuntimeError: no running event loop` | `create_task` called outside a running loop | Call it from inside a coroutine started by `asyncio.run` |
The second row is the most common. This looks concurrent but is not:
result_a = await asyncio.create_task(fetch("a", 0.2))
result_b = await asyncio.create_task(fetch("b", 0.2))The first await finishes before the second task exists, so the total time is 0.4 seconds.
Tasks share one thread
Tasks give you concurrency, not parallelism. All tasks run on one thread, and they switch only at await points. Two consequences follow:
- A task that computes for a long time without awaiting blocks every other task, including timers. Use a process pool for CPU-heavy work, or
asyncio.to_threadfor blocking I/O calls. - Code between two
awaitpoints runs without interruption by other tasks. That makes many small updates to shared state safe without locks. It stops being true the moment you add anawaitin the middle of an update.
import asyncio
import time
def blocking_read():
time.sleep(0.2) # stands in for a synchronous library call
return "data"
async def ticker():
for _ in range(3):
print("tick")
await asyncio.sleep(0.05)
async def main():
tick_task = asyncio.create_task(ticker())
data = await asyncio.to_thread(blocking_read)
await tick_task
print(data)
asyncio.run(main())The ticks keep arriving while the blocking call runs in a worker thread. If you replaced to_thread with a direct blocking_read() call, the ticker could not start until the call returned.
What create_task does not give you
create_task starts work, but it does not manage it. It has no built-in way to wait for a group of tasks, stop siblings when one fails, or guarantee that no task outlives the function that created it. Later chapters address these gaps with asyncio.gather and asyncio.TaskGroup. Understanding the single-task behavior here makes those tools easier to reason about, because they are built on the same Task objects.
Exercise
A program creates three tasks with asyncio.create_task(fetch(name, d)) using delays of 0.3, 0.1, and 0.2 seconds. It then awaits them in that order: the 0.3 task, then the 0.1 task, then the 0.2 task. Roughly how long does the whole sequence take, and why? How long would it take if each task were created and awaited on one line, with no overlap?
Show answer
About 0.3 seconds. All three tasks start running as soon as the first await yields to the loop, so their sleeps overlap. By the time the 0.3 task finishes, the other two are already done, and awaiting them returns immediately. Total time is the longest delay, not the sum. With creation and awaiting on one line per task, nothing overlaps and the time is the sum, about 0.6 seconds.