本文代码来源于网上流传的 c++ 23种设计模式.pdf,在源码的基础上进行了简单的理解说明和改动,以备随时查阅更正(也是我写博客的初衷之一),如有侵权或者冒犯,请及时联系本人。
mail: nix.hedgehog4.next at gmail dot com
学习设计模式,不应太在意一些概念和名称的问题,很多时候它们只是帮你理解这样设计的原理和本质。至少我在学习设计模式的时候 有这样的感受。设计模式是前人经验的总结,理解消化是最重要的,而不是硬套照搬。
我觉得学习设计模式的最重要的是理解学习其中资源分配、组合和管理的想法办法以及思想。好吧,你可以嗤之以鼻了。
下面来说说并发编程中的两种设计模式:Proactor 和 Reactor;
英文部分引用地址 :http://www.artima.com/articles/io_design_patterns.html
简要翻译:(绿色为笔者注释)
系统I/O 分为 阻塞,非阻塞同步,分阻塞异步。这篇文章已经讲得很清楚了。
我们先关注读操作,写类似。
Reactor:(可以结合开源网络库muduo 来理解,muduo 抽象得不错 ,学习一般从main 开始)
1. An event handler declares interest in I/O events that indicate readiness for read on a particular socket
2. The event demultiplexor waits for events
3. An event comes in and wakes-up the demultiplexor, and the demultiplexor calls the appropriate handler
(以上两步基本对应 muduo::EventLoop 的操作 这是个管理类 使用Poller发现事件,
然后交给Channel(socket封装类)处理)
4. The event handler performs the actual read operation, handles the data read, declares renewed interest in I/O events,
and returns control to the dispatcher
(在muduo 中 handler 基本是用户传处理函数地址 一路set过去,使用的是 boost::function 和 boost::bind..
(好像和duilib 源码里面的delegate一个意思)
//当然也可以使用回调, 比如抽象一个回调基类IHandler 让所有调用去重写)
Proactor:
1. A handler initiates an asynchronous read operation (note: the OS must support asynchronous I/O).
In this case, the handler does not care about I/O readiness events,
but is instead registers interest in receiving completion events.
2. The event demultiplexor waits until the operation is completed
3. While the event demultiplexor waits, the OS executes the read operation in a parallel kernel thread,
puts data into a user-defined buffer, and notifies the event demultiplexor that the read is complete
(epoll 中有两种玩法 ET LT, 如果用户没有及时响应,LT会一直触发直到一些错误的产生,而ET只触发一次 。
触发 即epoll_wait 返回的可用连接)
4. The event demultiplexor calls the appropriate handler;
5. The event handler handles the data from user defined buffer,
starts a new asynchronous operation, and returns control to the event demultiplexor.
//////////////////////////////////////////END//////////////////////////////////////////