I/O multiplexing lets a thread monitor multiple I/O sources through an operating-system notification interface. An application registers interest in events, then polls for notifications and handles sources that are ready. This avoids dedicating a thread to each connection and can reduce context-switching overhead. section 10.1.2 section 10.2.1
In a synchronous server, a socket read may block the thread until a message arrives. With multiplexing, an asynchronous server can monitor several connections and react when a socket becomes readable or writable. It can also start a response and work on other tasks while the operating system sends it. section 10.1.1
An event loop uses multiplexing as its dispatcher:
- Register interest in sources such as sockets, files, or timers. section 10.1.2
- Poll for events, process each notification, and run scheduled tasks; then repeat. section 10.1.2
- Use a polling timeout to avoid wasting CPU while idle without blocking forever. section 10.1.2
struct EventLoop {
// Holds registered event sources like sockets, files, timers
sources: Vec<EventSource>,
}
impl EventLoop {
fn run(&mut self) {
loop {
// Create a new collection to store events
let mut events = Events::new();
// Poll for new events with a timeout
self.poll(&mut events, Duration::from_millis(100));
// Process each event that was found
for event in events.iter() {
self.process_event(&event);
}
// Run any scheduled tasks
self.run_scheduled_tasks();
}
}
}
This Rust event-loop sketch polls with a timeout, processes returned events, and runs scheduled tasks. The OS-specific poll implementation is not shown. section 10.1.2
Handling a network request
An event loop can accept a connection, register interest in reading its socket, and receive a notification when data arrives. It then processes the request and handles a writable event to send a response. The same loop can also handle expired timers. section 10.1.2
Multiplexing supports high-connection workloads such as web servers and real-time messaging. The surrounding asynchronous design can improve latency, but resource management and error handling may become more complex; backpressure, timeouts, and cancellation also need attention. section 10.2.1 section 10.8
