-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEventLoop.cpp
122 lines (103 loc) · 2.57 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include "EventLoop.h"
#include "Channel.h"
#include "Epoll.h"
#include "IFRun.h"
#include "TimerQueue.h"
#include <sys/eventfd.h>
#include <unistd.h>
#include <iostream>
using namespace std;
EventLoop::EventLoop()
:pPoller(new Epoll),
ieventfd(createEventfd()),
pWakeupChannel(new Channel(this, ieventfd)),
pTimerQueue(new TimerQueue(this))
{
//ieventfd = createEventfd();
//pWakeupChannel = new Channel(this, ieventfd);
pWakeupChannel->setCallBack(this);
pWakeupChannel->enableReading();
}
EventLoop::~EventLoop()
{
delete pPoller;
delete pWakeupChannel;
delete pTimerQueue;
}
void EventLoop::update(Channel *_pChannel)
{
pPoller->update(_pChannel);
}
void EventLoop::loop()
{
while(1)
{
std::vector<Channel*> vecChannel;
pPoller->poll(vecChannel);
for (std::vector<Channel *>::iterator itChannel = vecChannel.begin(); itChannel != vecChannel.end(); ++itChannel)
{
(*itChannel)->handleEvent();
}
handlePendingRuns();
}
}
int EventLoop::createEventfd()
{
int ret = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
if (ret < 0)
std::cout << "create eventfd failed" << std::endl;
return ret;
}
void EventLoop::queueLoop(IFRun * pRun, void *param)
{
Runner runner(pRun, param);
vecRun.push_back(runner);
wakeup();
}
void EventLoop::wakeup()
{
uint64_t one = 1;
ssize_t n = write(ieventfd, &one, sizeof(one));
if (n != sizeof(one))
{
std::cout << "write data into eventfd error" << std::endl;
}
}
void EventLoop::handleRead()
{
uint64_t rdata = 0;
ssize_t n = read(ieventfd, &rdata, sizeof(rdata));
if (n != sizeof(rdata))
{
std::cout << "read data from eventfd error" << std::endl;
}
}
void EventLoop::handleWrite()
{
}
void EventLoop::handlePendingRuns()
{
vector<Runner> tempRuns;
tempRuns.swap(vecRun);
vector<Runner>::iterator it;
for(it = tempRuns.begin(); it != tempRuns.end(); ++it)
{
(*it).doRun();
}
}
long EventLoop::runAt(Timestamp when, IFRun* pRun)
{
return pTimerQueue->addTimer( pRun, when, 0.0);
}
long EventLoop::runAfter(double delay, IFRun* pRun)
{
return pTimerQueue->addTimer(pRun, Timestamp::nowAfter(delay), 0.0);
}
long EventLoop::runEvery(double interval, IFRun* pRun)
{
return pTimerQueue->addTimer(pRun, Timestamp::nowAfter(interval), interval);
}
void EventLoop::cancelTimer(long timerId)
{
pTimerQueue->cancelTimer(timerId);
}