Describe how asyncio and the event loop work (including selectors and epoll).
Asked at
AI answer
asyncio makes it possible to perform many I/O-waiting operations without using a separate thread for each one. A coroutine pauses at await while waiting for a result, and the event loop runs another coroutine that is ready. When the awaited operation completes, the coroutine returns to the queue of ready tasks.
For network I/O, the event loop uses non-blocking sockets and a mechanism for waiting until file descriptors are ready. Python’s selectors abstraction selects an appropriate system mechanism—for example, epoll on Linux, kqueue on macOS/BSD, or another available option. The event loop registers file descriptors and the events it is waiting for; while sockets are not ready, the system waits for events instead of making the application continuously poll each socket. After receiving a notification, the event loop schedules the corresponding callbacks or coroutines.
This is efficient for I/O-bound workloads, but it does not mean that CPU code runs in parallel: a long-running synchronous operation blocks the event loop. It should be moved to an executor or a process.
Also asked at ГК МЕДСИ
- [name] asked: How does memory management work in Python (garbage collector, reference counting)?
- What is the difference between TaskGroup and the gather function in the asyncio library in Python?
- What solutions did you implement to work around ChatGPT being unavailable from Russian IP addresses?
- How do you scale web application workers (for example, in FastAPI or Django), and which server did you use on your project?
- What blocks the event loop, how do you detect it in production, and what should you do about blocking code?
Similar questions
- Tell me about asyncio: what is it and how does it work?
- Conceptually, how is the Event Loop in asyncio structured?
- Explain step by step what happens when asyncio.run(main()) is executed, where main awaits an HTTP request: the roles of the coroutine, event loop, await, Future, and socket.
- Give two examples of tasks: when is it better to use asyncio, and when threading?
- Does asyncio have an advantage over multithreading for 10,000 I/O requests?