-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTimer.cpp
More file actions
123 lines (114 loc) · 3.84 KB
/
Timer.cpp
File metadata and controls
123 lines (114 loc) · 3.84 KB
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 <iostream>
#include <vector>
#include <list>
#include <pthread.h>
#include <unistd.h>
#include <sys/time.h>
using namespace std;
class Request{
public:
int id;
int timeout;
int interval;
void (*callback)(void* arg);
Request():timeout(0), callback(NULL){};
Request(int t, int intvl, void(*fn) (void* arg)):timeout(t), interval(intvl), callback(fn)
{};
};
enum STATUS{
INIT = 0,
RUNNING = 1,
STOPPED = 2,
};
class TimerProcess{
private:
int status;
list<Request> timerList;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
bool exitFlag;
const int DEFAULT_TIME = 1;
time_t getNowTime(){ // get current time in seconds
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec;
}
int insert(Request& req){
// pthread_mutex_lock(&mutex);
if(timerList.empty()){
timerList.push_back(req);
}
else{
long now = getNowTime();
for(auto it = timerList.begin();
it != timerList.end();
it++){
if((*it).timeout > now){
timerList.insert(it, req);
break;
}
}
}
// pthread_mutex_unlock(&mutex);
}
public:
TimerProcess(){
status = INIT;
exitFlag = false;
}
void start(void){
cout<<"START timer thread"<<endl;
status = RUNNING;
while(!exitFlag){
int sleepTime = DEFAULT_TIME;
int now = getNowTime();
pthread_mutex_lock(&mutex);
for(auto it = timerList.begin();
it != timerList.end();
it++){
time_t timeout = (*it).timeout;
if(timeout > now){
sleepTime = timeout - now;
break;
}
int interval = (*it).interval;
void (*fn)(void*) = (*it).callback;
if(fn != NULL) fn((void *)interval);
//timerList.erase(it);
//Request newReq(now+interval, interval, fn);
//insert(newReq);
}
pthread_mutex_unlock(&mutex);
cout<<"Sleeping "<<sleepTime<<" s..."<<endl;
sleep(sleepTime);
}
status = STOPPED;
cout<<"EXIT timer thread"<<endl;
}
void stop(void){
exitFlag = true;
cout<<"STOPPING timer"<<endl;
}
int addTimer(int interval, void (*fn)(void * arg)){
long now = getNowTime();
int timeout = now + interval;
Request req(timeout, interval, fn);
insert(req);
}
int cancelTimer(int id){
}
};
//
void test_callback(void *arg){
cout<<"Call back is called "<<(int)arg<<endl;
}
void test_callback2(void *arg){
cout<<"Call back is called "<<(int)arg<<endl;
}
int main(void){
TimerProcess t;
void (*fn)(void*) = test_callback;
t.addTimer(1, fn);
t.addTimer(3, test_callback2);
t.start();
return 0;
}