asyncio is Python’s built-in way to run many waiting tasks at the same time in a single thread. Think of one cook making rice, dal and fish curry together: while the rice simmers, the cook starts the dal instead of standing and watching the pot. In code, every place where a task waits is marked with await, and asyncio switches to another task there. This lesson covers async def, await, gather, task groups, timeouts and queues.
In this lesson you will learn
- Coroutines with
async defandawait - Starting the event loop with
asyncio.run - Running tasks together with
gatherandTaskGroup - Timeouts with
wait_for - Passing work between tasks with
asyncio.Queue
You should know functions and have read threading, which solves a similar problem in a different way.
async, await and gather
import asyncio
import time
async def cook(dish, minutes):
print(f" start {dish}")
await asyncio.sleep(minutes / 10) # 1 'minute' = 0.1 s; other tasks run meanwhile
print(f" {dish} ready")
return dish
async def main():
start = time.perf_counter()
# gather runs the coroutines concurrently and keeps the result order
dishes = await asyncio.gather(cook("rice", 3), cook("dal", 2), cook("fish curry", 4))
print("served:", dishes)
print(f"took about {time.perf_counter() - start:.1f}s instead of 0.9s")
asyncio.run(main())
# Calling an async function does not run it; it creates a coroutine object
async def greet():
return "hello"
coro = greet()
print(type(coro).__name__)
print(asyncio.run(coro))
Output
start rice
start dal
start fish curry
dal ready
rice ready
fish curry ready
served: ['rice', 'dal', 'fish curry']
took about 0.4s instead of 0.9s
coroutine
hello
async defdefines a coroutine function. Calling it does not run its body; it returns a coroutine object, as the last lines show. Something mustawaitit or pass it toasyncio.run.asyncio.run(main())starts the event loop, the scheduler that decides which task runs next, and runsmainuntil it finishes.await asyncio.sleep(...)pauses this task and lets others run. All three dishes start straight away, and each one is ready when its own timer ends: dal first, fish curry last.gatherruns the three coroutines together and returns their results in the order you passed them, not the order they finished. The total time is about as long as the slowest dish, 0.4 seconds, instead of the 0.9 seconds the three would take one after another.- Use
asyncio.sleep, nevertime.sleep, inside a coroutine.time.sleepblocks the whole thread, so no other task can run.
TaskGroup, Timeouts and Queues
import asyncio
# TaskGroup (Python 3.11+): start tasks, wait for all, cancel the rest on error
async def fetch_price(item, delay, price):
await asyncio.sleep(delay)
return item, price
async def prices():
async with asyncio.TaskGroup() as tg:
t1 = tg.create_task(fetch_price("rice", 0.2, 75))
t2 = tg.create_task(fetch_price("oil", 0.1, 190))
print("prices:", dict([t1.result(), t2.result()]))
# wait_for: give up if something takes too long
async def slow_server():
await asyncio.sleep(2)
return "finally!"
async def with_timeout():
try:
await asyncio.wait_for(slow_server(), timeout=0.2)
except TimeoutError:
print("gave up after 0.2s")
# Queue: producers and consumers that take turns without threads
async def producer(q):
for n in range(1, 6):
await q.put(f"order-{n}")
await asyncio.sleep(0.01)
await q.put(None) # signal: no more orders
async def consumer(q):
handled = []
while (order := await q.get()) is not None:
handled.append(order)
print("handled:", handled)
async def main():
await prices()
await with_timeout()
q = asyncio.Queue(maxsize=2)
await asyncio.gather(producer(q), consumer(q))
asyncio.run(main())
Output
prices: {'rice': 75, 'oil': 190}
gave up after 0.2s
handled: ['order-1', 'order-2', 'order-3', 'order-4', 'order-5']
asyncio.TaskGroup(Python 3.11 and later) starts tasks withcreate_task. When theasync withblock ends, every task has finished, soresult()is safe to call. If one task fails, the group cancels the others and raises the error.asyncio.wait_for(..., timeout=0.2)cancels a task that takes too long and raisesTimeoutError. The slow server never gets to reply.asyncio.Queue(maxsize=2)connects a producer and a consumer.await q.put(...)waits when the queue is full andawait q.get()waits when it is empty. PuttingNonetells the consumer there is no more work.- The walrus operator in
while (order := await q.get()) is not Nonegets the next item and checks it in a single line.
asyncio or Threads?
| asyncio | Threads | |
|---|---|---|
| Switches tasks | Only at await | At any moment |
| Race conditions | Rare, because switches are visible | Need locks |
| Scales to | Thousands of connections | Tens to hundreds of threads |
| Libraries | Must be async (for example aiohttp) | Works with ordinary libraries |
Common Mistakes
- Forgetting
await. The coroutine never runs, and Python warns “coroutine was never awaited”. - Calling blocking code such as
time.sleeporrequests.getin a coroutine. Use async versions, orawait asyncio.to_thread(func). - Calling
asyncio.runinside a running loop, for example inside another coroutine. Useawaitinstead. - Creating tasks without keeping a reference or awaiting them, so errors go unnoticed. A
TaskGroupavoids this.
Practice Exercises
Exercise 1. Write a coroutine countdown(name, n) that prints name n down to 1 with a 0.1-second pause, and run two countdowns at the same time.
Show answer
import asyncio
async def countdown(name, n):
for i in range(n, 0, -1):
print(name, i)
await asyncio.sleep(0.1)
async def main():
await asyncio.gather(countdown("A", 3), countdown("B", 2))
asyncio.run(main()) # A 3, B 2, A 2, B 1, A 1
Exercise 2. Run an ordinary blocking function slow_sum(n) from a coroutine without freezing other tasks.
Show answer
result = await asyncio.to_thread(slow_sum, 10_000_000)
to_thread runs the function in a worker thread and lets the event loop keep serving other tasks.
Frequently Asked Questions
Does asyncio make my code use several CPU cores?
No. asyncio runs in one thread, so it helps only with waiting. For heavy calculation use processes, for example ProcessPoolExecutor.
Where is asyncio used in practice?
In web frameworks such as FastAPI, chat servers and bots, web scrapers, and any program that talks to many network services at once.
Summary
async defcreates coroutines;awaitmarks where a task may pause.asyncio.runstarts the event loop;gatherandTaskGrouprun tasks together.wait_foradds timeouts;asyncio.Queuepasses work between tasks.- Never block the loop with
time.sleepor other blocking calls.
Next: Python heapq and bisect.
