forked from chunyi1994/cppevent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheventloop.cpp
112 lines (98 loc) · 2.43 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
#include "eventloop.h"
#include "poller.h"
#include "event.h"
#include <algorithm>
#include "utils.h"
namespace cppevent{
EventLoop::EventLoop():
quit_(false),
poller_(std::make_shared<Poller>()),
taskQueue_(){}
EventLoop::~EventLoop(){}
void EventLoop::loop()
{
while(!quit_){
activeEvents_.clear();
processTimeEvent();
doTask();//执行投递的一些任务
poller_->wait(&activeEvents_); //epoll的wait
std::for_each(activeEvents_.begin(), activeEvents_.end(), [](Event *event){
event->handleEvent();
});
}
}
void EventLoop::addEvent(Event *event)
{
poller_->addEvent(event);
}
void EventLoop::addTimeEvent(const TimeEventPtr &timeEventPtr)
{
timeQueue_.push(timeEventPtr);
}
void EventLoop::addTask(const EventLoop::TaskFunc &task)
{
taskQueue_.push(task);
}
void EventLoop::doTask()
{
while(!taskQueue_.empty()){
TaskFunc func = *(taskQueue_.front());
taskQueue_.pop();
func();
}
}
void EventLoop::processTimeEvent()
{
while(!timeQueue_.empty())
{
Time nowTime;
nowTime.now();
TimeEventPtr timeEventPtr = timeQueue_.top();
if(timeEventPtr->getTime() < nowTime)
{
timeQueue_.pop();
timeEventPtr->executeCallback();
if(timeEventPtr->type() == TIME_TYPE_ALWAYS)
{
timeEventPtr->setNextTime();
timeQueue_.push(timeEventPtr);
}
}
else
{
return;
}
}
}
void EventLoop::quit()
{
quit_ = true;
}
TimeEventPtr EventLoop::runAfter(const Time &after, const TimeCallback &cb)
{
Time atTime;
atTime.now();
atTime.add(after);
TimeEventPtr timeEvent = std::make_shared<TimeEvent>(atTime);
timeEvent->setTimeCallback(cb);
addTimeEvent(timeEvent);
return timeEvent;
}
TimeEventPtr EventLoop::runAt(const Time &atTime, const TimeCallback &cb )
{
TimeEventPtr timeEvent = std::make_shared<TimeEvent>(atTime);
timeEvent->setTimeCallback(cb);
addTimeEvent(timeEvent);
return timeEvent;
}
TimeEventPtr EventLoop::runEvery(const Time &interval, const TimeCallback &cb)
{
Time atTime;
atTime.now();
TimeEventPtr timeEvent = std::make_shared<TimeEvent>(atTime, TIME_TYPE_ALWAYS);
timeEvent->setInterval(interval);
timeEvent->setTimeCallback(cb);
addTimeEvent(timeEvent);
return timeEvent;
}
}