-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEventLoop.cpp
74 lines (64 loc) · 1.87 KB
/
EventLoop.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include "EventLoop.h"
#include "MemoryPool.h"
#include "Logging.h"
bool EventLoop::quit = false;
void EventLoop::setquit(int a){
quit = true;
}
EventLoop::EventLoop()
: poller(newElement<Epoll>(),deleteElement<Epoll>),
looping(false),
timermanager(newElement<TimerManager>(),deleteElement<TimerManager>)
{
wakeupfd = Eventfd(0, EFD_NONBLOCK|EFD_CLOEXEC);
}
void EventLoop::addPoller(SP_Channel channel){
poller->add(channel);
}
void EventLoop::updatePoller(SP_Channel channel){
poller->update(channel);
}
void EventLoop::removePoller(SP_Channel channel){
poller->del(channel);
}
void EventLoop::addTimer(SP_Channel channel, int timeout){
timermanager->addTimer(std::move(channel), timeout);
}
void EventLoop::queueInLoop(Functor&& cb){
MutexLockGuard lock(mutex);
pendingfunctorq.emplace_back(std::move(cb));
uint64_t buffer = 1;
if(write(wakeupfd, &buffer, sizeof(buffer)) < 0){
LOG<<"wake up write error";
}
}
void EventLoop::doPendingFunctors(){
uint64_t buffer;
if(read(wakeupfd, &buffer, sizeof(buffer)) < 0){
LOG << "wake up read error";
}
std::vector<Functor> next;
MutexLockGuard lock(mutex);
next.swap(pendingfunctorq);
for(auto& ti : next){
ti();
}
}
void EventLoop::loop(){
wakeupchannel = SP_Channel(newElement<Channel>(shared_from_this()),
deleteElement<Channel>);
wakeupchannel->setFd(wakeupfd);
wakeupchannel->setRevents(EPOLLIN|EPOLLET);
wakeupchannel->setReadhandler(std::bind(&EventLoop::doPendingFunctors,
shared_from_this()));
addPoller(wakeupchannel);
std::vector<SP_Channel> temp;
while(!quit){
poller->poll(temp);
for(auto& ti : temp){
ti->handleEvent();
}
temp.clear();
timermanager->handleExpiredEvent();
}
}