-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathalarm.cpp
72 lines (59 loc) · 1.42 KB
/
alarm.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
#include "alarm.h"
void alarm_triggered(int signum){
Alarm::Handler::inst().reset(signum);
}
Alarm::Handler::Handler() : nextid(0) {
signal(SIGALRM, alarm_triggered);
signal(SIGUSR1, alarm_triggered);
}
Alarm::Handler & Alarm::Handler::inst() {
static Handler instance;
return instance;
}
int Alarm::Handler::add(Time timeout, callback_t fn){
Entry entry(nextid, fn, timeout);
alarms.push_back(entry);
nextid = (nextid + 1) & 0x3FFFFFFF; //sets a limit of 2^30 alarms, but keeps them in the positive range
reset(SIGALRM);
return entry.id;
}
bool Alarm::Handler::cancel(int id){
if(id < 0)
return false;
bool found = false;
for(std::vector<Entry>::iterator a = alarms.begin(); a != alarms.end(); ){
if(a->id == id){
a->called = true;
found = true;
}
if(a->called)
a = alarms.erase(a);
else
++a;
}
return found;
}
void Alarm::Handler::reset(int signum){
Time now;
double next = 0;
for(std::vector<Entry>::iterator a = alarms.begin(); a != alarms.end(); ++a){
double cur = a->timeout - now;
if(cur <= 0 || signum == SIGUSR1){
if(!a->called){
a->fn();
a->called = true;
}
}else{
if(next == 0 || next > cur)
next = cur;
}
}
if(next > 0){
struct itimerval timeout;
timeout.it_interval.tv_usec = 0;
timeout.it_interval.tv_sec = 0;
timeout.it_value.tv_usec = (next - (int)next)*1000000;
timeout.it_value.tv_sec = next;
setitimer(ITIMER_REAL, &timeout, NULL);
}
}