Python asyncio
| created | 2026-02-26 16:12 |
| modified | 2026-05-27 07:51 |
| tags | python, concurrency |
| status | start |
asyncio is a Python library enabling concurrent operations using the async/await syntax. Under the hood, it’s all coroutines.
== (?) cooperative multitasking; cooperative concurrency ==
asyncio works by establishing a singular global event loop. Coroutines (or “tasks”) are defined with async def, and the event loop constantly monitors the existing tasks, running them as needed. asyncio is fundamentally single-threaded.
asyncio vs regular threading
| - | asyncio | threading |
|---|---|---|
| Memory | ~KB per coroutine | ~1-8MB per thread |
| Scaling | 100k+ concurrent tasks | Hundreds at most |
| Context switch | Cheap (userspace) | Expensive (kernel) |
| Race conditions | Only at await points | Anywhere - need locks |
| Ecosystem | Everything must be async-aware | Any code works |
| Blocking | Breaks everything | Fine |
| Complexity | Harder to understand | Simpler mental model |
| Best for | High-volume IO | Legacy/blocking code |
Using asyncio in combination with threads
I would recommend creating a single event loop in a background thread and have it service all your async needs. It doesn’t matter that your coroutines never end; asyncio is perfectly capable of executing multiple such functions in parallel. (source - stackoverflow)