Reading history

Python asyncio: async, await, gather and TaskGroup

6 min read 3 views

Learn Python asyncio: coroutines with async and await, asyncio.run, gather, TaskGroup, timeouts with wait_for and producer-consumer queues.

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 def and await
  • Starting the event loop with asyncio.run
  • Running tasks together with gather and TaskGroup
  • 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 def defines a coroutine function. Calling it does not run its body; it returns a coroutine object, as the last lines show. Something must await it or pass it to asyncio.run.
  • asyncio.run(main()) starts the event loop, the scheduler that decides which task runs next, and runs main until 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.
  • gather runs 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, never time.sleep, inside a coroutine. time.sleep blocks 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 with create_task. When the async with block ends, every task has finished, so result() 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 raises TimeoutError. 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 and await q.get() waits when it is empty. Putting None tells the consumer there is no more work.
  • The walrus operator in while (order := await q.get()) is not None gets the next item and checks it in a single line.

asyncio or Threads?

asyncioThreads
Switches tasksOnly at awaitAt any moment
Race conditionsRare, because switches are visibleNeed locks
Scales toThousands of connectionsTens to hundreds of threads
LibrariesMust be async (for example aiohttp)Works with ordinary libraries

Common Mistakes

  1. Forgetting await. The coroutine never runs, and Python warns “coroutine was never awaited”.
  2. Calling blocking code such as time.sleep or requests.get in a coroutine. Use async versions, or await asyncio.to_thread(func).
  3. Calling asyncio.run inside a running loop, for example inside another coroutine. Use await instead.
  4. Creating tasks without keeping a reference or awaiting them, so errors go unnoticed. A TaskGroup avoids 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 def creates coroutines; await marks where a task may pause.
  • asyncio.run starts the event loop; gather and TaskGroup run tasks together.
  • wait_for adds timeouts; asyncio.Queue passes work between tasks.
  • Never block the loop with time.sleep or other blocking calls.

Next: Python heapq and bisect.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *