-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathtimer.c
More file actions
112 lines (90 loc) · 2.59 KB
/
timer.c
File metadata and controls
112 lines (90 loc) · 2.59 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
#include<stdio.h>
#include<stdint.h>
#include<stdlib.h>
#include<time.h>
#include<unistd.h>
#define WHEEL_BIN_NUMBER 10
#define GRANULARITY 1000000
typedef void (*timeout_handler)();
typedef struct node {
struct node *next;
int timestamp;
timeout_handler timeout_cb;
} Node, *pNode;
typedef struct timing_wheel {
int cur_slot;
int granularity;
Node nodes[WHEEL_BIN_NUMBER];
} TWheel, *pTWheel;
pTWheel init_time_wheel(int gran) {
pTWheel new_wheel = (pTWheel) malloc(sizeof(TWheel));
new_wheel->granularity = gran;
new_wheel->cur_slot = 0;
int i;
for (i; i < WHEEL_BIN_NUMBER; i++) {
new_wheel->nodes[i].next = NULL;
}
return new_wheel;
}
int install_handler(pTWheel twheel, int deadline, timeout_handler new_cb) {
int ret = 0;
if (deadline/twheel->granularity >= WHEEL_BIN_NUMBER) {
printf("Deadline exceed timing wheel size\n");
return -1;
}
int index = (twheel->cur_slot + ((deadline/(twheel->granularity))))%WHEEL_BIN_NUMBER;
pNode iterator = &(twheel->nodes[index]);
while(iterator->next) {
iterator = iterator->next;
}
pNode new_node = (pNode) malloc(sizeof(Node));
new_node->timeout_cb = new_cb;
new_node->timestamp = deadline;
new_node->next = NULL;
iterator->next = new_node;
return ret;
}
void tick(pTWheel twheel) {
int i;
pNode iterator = &twheel->nodes[twheel->cur_slot];
while(iterator->next) {
pNode tmp = iterator->next;
tmp->timeout_cb();
printf("Callback at %d deadline triggers\n", tmp->timestamp);
iterator->next = iterator->next->next;
free(tmp);
}
twheel->cur_slot = (twheel->cur_slot+1)%WHEEL_BIN_NUMBER;
}
void print_task() {
printf("Hi1\n");
}
void print_task2() {
printf("Hi2\n");
}
void print_task3() {
printf("Hi3\n");
}
int main(void) {
int ret = 0;
pTWheel new_wheel = init_time_wheel(GRANULARITY);
timeout_handler cb = print_task;
install_handler(new_wheel, 4*GRANULARITY, cb);
install_handler(new_wheel, 4.25*GRANULARITY, cb);
install_handler(new_wheel, 4.9*GRANULARITY, cb);
cb = print_task2;
install_handler(new_wheel, 8*GRANULARITY, cb);
cb = print_task3;
install_handler(new_wheel, 8*GRANULARITY, cb);
install_handler(new_wheel, 12*GRANULARITY, cb);
int count = 0;
while(count < 15) {
tick(new_wheel);
usleep(GRANULARITY);
printf("Time: %d\n", count++);
if (count == 8) {
install_handler(new_wheel, 4*GRANULARITY, cb);
}
}
return 0;
}