liveBook · Manning

Reactor pattern

As explained in Grokking Concurrency

The reactor pattern is an event-driven concurrency pattern that demultiplexes readiness notifications and dispatches them to handlers, typically through a single event loop.

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

How Grokking Concurrency covers it

How deep it goes
Explains the event loop, multiplexing, sources, handlers, and callbacks, but stops short of detailed implementation code.
Examples
Uses a pizza server with server and client sockets, select, and accept, read, and write handlers.
What you can do after
Build event-driven I/O applications by registering sources, waiting with select, and dispatching readiness callbacks.
How it connects
Connects event-based concurrency with nonblocking I/O, I/O multiplexing, callbacks, and client-server applications.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Concurrency. The section links point to the parts of the book it draws on.