NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Senior0 views

Describe how asyncio and the event loop work (including selectors and epoll).

Practice

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.