when learning the reactor model today, I referred to the code written by others.
reference blog address: https://blog.csdn.net/u011693.
the following are the questions to be asked:
1.reactorreactor_impl
2.reactor
CPP rookie, also hope to be able to learn.
Source code:
reactor.h
-sharpinclude "event_handler.h"
-sharpinclude "event.h"
-sharpinclude "reactor_impl.h"
class ReactorImpl;
class Reactor {
public:
static Reactor& get_instance();
int regist(EventHandler* handler, Event evt);
void remove(EventHandler* handler);
void dispatch(int timeout = 0);
private:
Reactor();
~Reactor();
Reactor(const Reactor&);
Reactor& operator=(const Reactor&);
private:
ReactorImpl* _reactor_impl;
static Reactor reactor;
};
reactor.cpp
-sharpinclude "reactor.h"
-sharpinclude <assert.h>
-sharpinclude <new>
Reactor Reactor::reactor;
Reactor& Reactor::get_instance() {
return reactor;
}
Reactor::Reactor() {
_reactor_impl = new (std::nothrow)ReactorImpl();
assert(_reactor_impl != NULL);
}
Reactor::~Reactor() {
if (_reactor_impl != NULL) {
delete _reactor_impl;
_reactor_impl = NULL;
}
}
int Reactor::regist(EventHandler* handler, Event evt) {
return _reactor_impl->regist(handler, evt);
}
void Reactor::remove(EventHandler* handler) {
return _reactor_impl->remove(handler);
}
void Reactor::dispatch(int timeout) {
return _reactor_impl->dispatch(timeout);
}
reactor_impl.h
-sharpinclude <map>
-sharpinclude "event.h"
-sharpinclude "event_handler.h"
-sharpinclude "event_demultiplexer.h"
class ReactorImpl {
public:
ReactorImpl();
~ReactorImpl();
int regist(EventHandler* handler, Event evt);
void remove(EventHandler* handler);
void dispatch(int timeout = 0);
private:
EventDemultiplexer* _demultiplexer;
std::map<Handle, EventHandler*> _handlers;
};
reactor_impl.cpp
-sharpinclude "reactor_impl.h"
-sharpinclude <new>
-sharpinclude <assert.h>
-sharpinclude "epoll_demultiplexer.h"
ReactorImpl::ReactorImpl() {
_demultiplexer = new (std::nothrow)EpollDemultiplexer();
assert(_demultiplexer != NULL);
}
ReactorImpl::~ReactorImpl() {
std::map<Handle, EventHandler*>::iterator iter = _handlers.begin();
for(; iter != _handlers.end(); PPiter) {
delete iter->second;
}
if (_demultiplexer != NULL) {
delete _demultiplexer;
}
}
int ReactorImpl::regist(EventHandler* handler, Event evt) {
int handle = handler->get_handle();
if (_handlers.find(handle) == _handlers.end()) {
_handlers.insert(std::make_pair(handle, handler));
}
return _demultiplexer->regist(handle, evt);
}
void ReactorImpl::remove(EventHandler* handler) {
int handle = handler->get_handle();
// not check?
_demultiplexer->remove(handle);
std::map<Handle, EventHandler*>::iterator iter = _handlers.find(handle);
delete iter->second;
_handlers.erase(iter);
}
void ReactorImpl::dispatch(int timeout) {
_demultiplexer->wait_event(_handlers, timeout);
}