北飞

非一般的感觉
随笔 - 9, 文章 - 3, 评论 - 0, 引用 - 0
数据加载中……

并发编程模式-----Reactor

 

       Reactor是并发编程中的一种设计模式,它主要是用于派发/分离IO操作事件。这里所谓的IO事件也就是诸如read/writeIO操作。"派发/分离"就是将单独的IO事件通知到上层模块。了解Reactor模式的起源是因为看redis的代码,对其中网络处理部分的精巧处理感觉叹服,上网一查才知道原来其中用到了Reactor模式。

       Reactor模式处理网络事件一般按照以下方式进行:

      * 声明对于感兴趣的网络事件的处理接口(event_handler)

      * 事件多路分发器等待事件发生(select/epoll)

      * 当有事件触发时,程序调用注册好event_handler去处理对应事件。

      * event_handler调用实际的I/O操作,当有连接到达,则将其加入到I/O events中。

     以下用C++代码简单的描述一下Reactor模式。
    

    
 1class event_handler 
 2{
 3    public:
 4       virtual void handle_read_event(int fd) = 0;
 5       virtual void handle_write_event(int fd) = 0;
 6}
;
 7   
 8/*事件多路分发和回调事件处理接口*/
 9class dispatcher
10{
11    public:
12      void event_poll()
13   {
14            while(1)
15         {
16                    select(max_fd,&read_set,&write_set,NULL,NULL);

17                    if event in read_set
18                 {
19                           handler->handle_read_event(event.fd);
20                     }

21                    if event in write_set
22                 {
23                          handler->handle_write_event(event.fd);
24                     }

25              }

26        }

27
28       void set_handler(event_handler *handler)
29    {
30              m_handler = handler;
31       }

32       
33    private:
34       event_handler *m_handler;
35}
;
36 

       当然我们必须派生event_handler,实现具体的事件处理逻辑,上述的代码才能起作用。

posted on 2011-01-05 13:30 北飞 阅读(886) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理