解释“领导者/追随者”模式 [英] Explain "Leader/Follower" Pattern
问题描述
我似乎找不到一个领导/追随者模式的良好和可访问的解释。所有解释都可以简单地在某些问题的上下文中引用或是完全无意义的。
任何人都可以解释这种模式的工作原理,以及为什么以及如何通过更传统的异步IO模型提高性能?
正如您可能已经阅读的那样,该模式由4个组件组成:ThreadPool,HandleSet ,Handle,ConcreteEventHandler(实现EventHandler接口)。
你可以将它当作一个出租车站在晚上,所有的司机都在睡觉,除了一个,领导者。 ThreadPool是一个管理许多线程的车站 - 出租车。
领导者正在等待HandleSet上的IO事件,就像驱动程序等待客户端一样。 >
当客户端到达(以Handle识别IO事件的形式)时,领导者的驱动程序唤醒另一名司机成为下一个领导者,并为其乘客提供请求。 / p>
当他将客户端送到给定地址(调用ConcreteEventHandler并将Handle提交给它)时,下一位领导者可以同时为另一名乘客服务。
当司机完成后,他将出租车带回车站,如果车站不空,则睡着。否则他将成为领导者。
此模式的优点是:
- 线程之间没有通信是必需的,没有同步,
和共享内存(没有锁,互斥体)
需要。 - 更多可以添加ConcreteEventHandler而不影响任何其他
EventHandler - 由于多线程而使延迟最小化
是:
- 复杂
- 网络IO可能是瓶颈
I can't seem to find a good and accessible explanation of "Leader/Follower" pattern. All explanations either simply refer to it in the context of some problem, or are completely meaningless.
Can anyone explain to the the mechanics of how this pattern works, and why and how it improves performance over more traditional asynchronous IO models? Examples and links to diagrams are appreciated too.
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
这篇关于解释“领导者/追随者”模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!