Skip to content

asyncio

In one line

asyncio is the stdlib module providing the event loop and primitives for async programming.

In simple words

asyncio is Python's built-in async I/O framework. It provides:

  1. Event loop — asyncio.run() starts the loop that schedules and runs coroutines.
  2. Tasks — asyncio.create_task() wraps a coroutine to run concurrently.
  3. Gather — asyncio.gather() runs multiple coroutines concurrently and collects results.
  4. Primitives — asyncio.Lock, asyncio.Queue, asyncio.Semaphore for coordination.
  5. Streams — asyncio.open_connection() for async network I/O.

It's the foundation of async web frameworks like FastAPI, aiohttp, and uvicorn.

Example

python
import asyncio

async def worker(name, queue):
    while True:
        item = await queue.get()
        if item is None:
            queue.task_done()
            break
        print(f"{name} processed {item}")
        await asyncio.sleep(0.5)
        queue.task_done()

async def main():
    queue = asyncio.Queue()
    for i in range(5):
        await queue.put(i)
    await queue.put(None)  # Sentinel
    await asyncio.gather(worker("W1", queue))

asyncio.run(main())

asyncio.Queue provides async-safe communication between coroutines, like queue.Queue but for async code.

Common confusions

  • Confused with: threading

    The difference: asyncio uses a single thread and an event loop — coroutines cooperate by yielding at await. threading uses multiple OS threads with preemption and GIL. asyncio is lighter (thousands of coroutines) but requires async-compatible libraries.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary