High-load applications often spend much of their time waiting for data. The reactor pattern handles this with a single-threaded event loop: it waits for nonblocking I/O events, identifies which resources are ready, and dispatches each event to its registered callback. section 11.13 section 11.6
A reactor-based application combines four parts:
- Event sources generate events; examples include files, sockets, timers, and synchronization objects. section 11.6
- Event handlers are callbacks that process requests for particular sources, such as accepting connections, reading messages, or writing responses. section 11.6
- A synchronous event demultiplexer, such as select or a related operating-system mechanism, waits for specified events on a set of handles. section 11.6 section 11.11
- The reactor, or event loop, registers callbacks and invokes the appropriate handler when the demultiplexer reports a ready resource. section 11.6
A small server’s event flow
A pizza server can register its server socket and client sockets as event sources. An accept handler receives new connections, a read handler processes client messages, and a write handler sends responses. The event loop waits through select and dispatches whichever handler matches the ready socket. section 11.6
Use the reactor structure diagram to follow the path from event sources through notification and callback dispatch. section 11.6
