As you might have read, the pattern consists of 4 components: ThreadPool, HandleSet, Handle, ConcreteEventHandler (implements the EventHandler interface).
You can think of it as a taxi station at night, where all the drivers are sleeping except for one, the leader. The ThreadPool is a station managing many threads - cabs.
The leader is waiting for an IO event on the HandleSet, like how a driver waits for a client.
When a client arrives (in the form of a Handle identifying the IO event), the leader driver wakes up another driver to be the next leader and serves the request from his passenger.
While he is taking the client to the given address (calling ConcreteEventHandler and handing over Handle to it) the next leader can concurrently serve another passenger.
When a driver finishes he take his taxi back to the station and falls asleep if the station is not empty. Otherwise he become the leader.
The pros for this pattern are:
- no communication between the threads are necessary, no synchronization,
nor shared memory (no locks, mutexes)
are needed.
- more ConcreteEventHandlers can be added without affecting any other
EventHandler
- minimizes the latency because of the multiple threads
The cons are:
- complex
- network IO can be a bottleneck
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…