An event notification system lets the operating system track non-blocking sockets and notify an application when they are ready. Instead of blocking while waiting for bytes, the Python thread can run other code and resume the waiting task when I/O completes. section 1.6.1
The mechanism supports asyncio-style concurrency through a simple sequence:
- Hand a non-blocking I/O operation to the operating system. section 1.6.1
- Continue executing other Python code while the operating system tracks socket readiness. section 1.6.1
- Wake the task and process its result when the operation finishes. section 1.6.1
Operating systems provide different implementations: kqueue on FreeBSD and macOS, epoll on Linux, and IOCP on Windows. These mechanisms avoid the costly polling loop that repeatedly tries operations and catches BlockingIOError. section 1.6.1 section 3.3
A non-blocking server
A socket configured with setblocking(False) can accept connections without waiting. A hand-built loop that repeatedly calls accept and recv must catch unavailable-I/O errors, consuming nearly 100% CPU; event notification replaces that busy polling with readiness notifications. section 3.3
Figure 1.8 Making a non-blocking I/O request returns immediately and tells the O/S to watch sockets for data. This allows execute_other_code() to run right away instead of waiting for the I/O requests to finish. Later, we can be alerted when I/O is complete and process the response.
Trace how a non-blocking I/O request returns immediately, lets other code run, and later signals that socket data is ready. section 1.6.1
