码迷,mamicode.com
首页 > 其他好文 > 详细

libevent学习-reactor设计模式及代码示例

时间:2021-06-02 13:32:16      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:rtu   timeval   private   句柄   设计模式及   pre   turn   type   oid   


title: libevent学习-reactor设计模式及代码示例
date: 2021-01-22 11:39:35
tags: libevent
categories: libevent学习

Reactor Design Pattern

Reactor设计模式包含句柄(Handle)、Reactor、事件多路分发器(EventDemultiplexer)、事件处理器(EventHandler)和具体事件处理器(ConcreteEventHandler)
(1)Handle
(2)Reactor
(3)EventDemultiplexer
(4)EventHandler
(5)ConcreteEventHandler

Example

typedef unsigned int event_t;
typedef unsigned int Handle;

class EventHandler
{
public:
    virtual void handle_event(int event) = 0;
    virtual Handle get_handle() = 0;
    // ...
};

class ConcreteEventHandler : public EventHandler
{
public:
    virtual void handle_event(int event){}
    virtual Handle get_handle()
    {
        return handle;
    }

private:
    Handle handle;
};

class EventDemultiplexer
{
public:
    void register_event(Handle, event_t){}
    void remove_event(Handle){}
    void demultiplex(std::map<Handle, EventHandler*> *)
    {
    	// wait for event
        // wait block OK and handle ready
    }
};

class Reactor
{
public:
    int register_handler(EventHandler *pHandler, event_t event)
    {
    	Handle handle = pHandler->get_handle();
    	// if it is new handle, save it to mapHandleEventHandler
    	std::map<Handle, EventHandler*>::iterator it = this->mapHandleEventHandler.find(handle);
    	if (it != this->mapHandleEventHandler.end())
    	{
    		this->mapHandleEventHandler[handle] = pHandler;
    	}
        // call EventDemultiplexer register_event
        eventDemultiplexer.register_event(handle, event);
    }

    int remove_handler(EventHandler *pHandler, event_t event)
    {
    	handle_t handle = handler->GetHandle();
        m_handlers.erase(handle);
        eventDemultiplexer.remove_event(handle);
    }

    void handle_events(timeval *ptv)
    {
        // eventloop waiting event and call EventHandler callback function(handle_event)
        eventDemultiplexer.demultiplex(&mapHandleEventHandler);
        // call ConcreteEventHandler handle_event()
    }

private:
    EventDemultiplexer eventDemultiplexer;
    std::map<Handle, EventHandler*> mapHandleEventHandler;
};

libevent学习-reactor设计模式及代码示例

标签:rtu   timeval   private   句柄   设计模式及   pre   turn   type   oid   

原文地址:https://www.cnblogs.com/xl-cnblog/p/14819713.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!