-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTimerHeap.cpp
executable file
·193 lines (178 loc) · 5.39 KB
/
TimerHeap.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#include "TimerHeap.h"
#include "common.h"
#include "MutexLock.h"
#include "Condition.h"
#include "MutexLockGuard.h"
namespace netlib{
//创建timerfd
int createTimer()
{
int timerfd = timerfd_create(CLOCK_MONOTONIC, //系统重启到现在的时间
TFD_NONBLOCK | TFD_CLOEXEC);
if (timerfd < 0)
{
CHEN_LOG(ERROR,"create timerfd error");
}
return timerfd;
}
/*********堆的相关操作**************/
typedef std::vector<Entry>::iterator Iterator;
template<typename Comp>
int push_heap(Iterator begin,Iterator end,Comp comp)
{// 新加入结点 其父结点为(i - 1) / 2
int topIndex = 0;
int len = end-begin;
int holeIndex = len-1;
int parent = (holeIndex - 1) / 2;
Entry value = *(end-1);
while (holeIndex > topIndex && comp(*(begin + parent),*(begin + holeIndex)))
{
*(begin + holeIndex) = *(begin + parent);
holeIndex = parent;
parent = (holeIndex - 1) / 2;
}
*(begin + holeIndex) = value;
return holeIndex;
}
template<typename Comp>
void adjust_heap(Iterator begin, Iterator end, int holeIndex, int len,Comp comp)
{//从holeIndex开始调整
int nextIndex = 2 * holeIndex + 1;
while (nextIndex < len)
{
if (nextIndex < len - 1 && comp(*(begin + nextIndex), *(begin + (nextIndex + 1))))
++nextIndex;
if (comp(*(begin + nextIndex), *(begin + holeIndex)))
break;
std::swap(*(begin + nextIndex), *(begin + holeIndex));
holeIndex = nextIndex;
nextIndex = 2 * holeIndex + 1;
}
}
template<typename Comp>
void pop_heap(Iterator begin, Iterator end, Comp comp)
{
std::swap(*begin, *(end - 1));
int len = end - begin - 1;
adjust_heap(begin, end, 0, len,comp);
}
/*********堆的相关操作end**************/
struct timespec howMuchTimeFromNow(TimeStamp when)
{
int64_t microseconds = when.getMicrosecondsSinceEpoch()
- TimeStamp::now().getMicrosecondsSinceEpoch();
if (microseconds < 100)
{
microseconds = 100;
}
struct timespec ts;
ts.tv_sec = static_cast<time_t>(
microseconds / TimeStamp::kMicroSecondsPerSecond);
ts.tv_nsec = static_cast<long>(
(microseconds % TimeStamp::kMicroSecondsPerSecond) * 1000);
return ts;
}
//设置timerfd的超时时间
void resetTimerfd(int timerfd, TimeStamp expiration,int interval)
{
struct itimerspec newValue;
struct itimerspec oldValue;
bzero(&newValue, sizeof newValue);
bzero(&oldValue, sizeof oldValue);
struct timespec ts;
ts.tv_sec = interval;
ts.tv_nsec = 0;
newValue.it_value = howMuchTimeFromNow(expiration);
newValue.it_interval = ts;
int ret = ::timerfd_settime(timerfd, 0, &newValue, &oldValue);
if (ret)
{
CHEN_LOG(ERROR,"set timerfd error");
}
}
//timerFD是否被设为周期执行
//返回interval
int getInterval(int timerfd)
{
struct itimerspec oldValue;
int ret = ::timerfd_gettime(timerfd,&oldValue);
if(ret)
CHEN_LOG(ERROR,"get timerfd error");
return oldValue.it_interval.tv_sec;
}
TimerHeap::TimerHeap(EventBase* base):cond(mutex),
timerFD(createTimer()),timerChannel(base,timerFD,kReadEvent)
{
}
TimerHeap::~TimerHeap()
{
close(timerFD);
}
TimerId TimerHeap::addTimer(TimeStamp when,TimerCallback cb,int64_t interval)
{
MutexLockGuard mutexLock(mutex);
timers.push_back(Entry(when,cb));
int index = push_heap(timers.begin(),timers.end(),EntryComp());
resetTimerfd(timerFD,timers.begin()->first,interval);
//保存此定时器在timers中的位置并设置timerID
TimerId ids_size = timerIDs.size();
for(TimerId i=0;i<ids_size;i++)
if(timerIDs[i] == -1)
{
timerIDs[i] = index;
CHEN_LOG(DEBUG,"id:%d",i);
return i;
}
timerIDs.push_back(index);
//注册定时事件
timerChannel.onRead(std::bind(&TimerHeap::handle_read,this));
timerChannel.enableRead(true);
CHEN_LOG(DEBUG,"id:%d",ids_size);
return ids_size;
}
bool TimerHeap::cancel(TimerId timerId)
{
MutexLockGuard mutexLock(mutex);
int index = timerIDs[timerId];
if(-1 == index)
return false;
std::swap(timers[index],timers[timers.size()-1]);
timers.pop_back();
adjust_heap(timers.begin(),timers.end(),index,timers.size(),EntryComp());
timerIDs[timerId] = -1;
return true;
}
void TimerHeap::handle_read()
{
//把超时状态读取掉
uint64_t value;
read(timerFD, &value, 8);
CHEN_LOG(DEBUG,"read results:%lld",value);
reset();
}
//执行定时器的任务并将已到时间的定时器清除
void TimerHeap::reset()
{
TimeStamp now = timers.begin()->first;
while (!timers.empty() && timers.begin()->first == now)
{//处理同时任务,这里有潜在的bug,当这个循环的时间超过1s,会导致定时不准
timers.begin()->second();
int interval = getInterval(timerFD);
if(!interval)
{
pop_heap(timers.begin(), timers.end(), EntryComp());
timers.pop_back();
}
else
{//如果是周期执行的,更新TimeStamp并调整堆
TimeStamp newStamp(now.getMicrosecondsSinceEpoch()+
interval*TimeStamp::kMicroSecondsPerSecond);
timers.begin()->first = newStamp;
adjust_heap(timers.begin(),timers.end(),0,timers.size(),EntryComp());
}
}
int interval = getInterval(timerFD);
if(!timers.empty())
resetTimerfd(timerFD,timers.begin()->first,interval);
}
}