1+ #include <stdio.h>
2+ #include <stdint.h>
3+
4+ #define WHEEL_BIN_NUMBER 10
5+ #define GRANULARITY 1000000
6+
7+ typedef void (* timeout_handler )();
8+
9+ typedef struct node {
10+ struct node * next ;
11+ int timestamp ;
12+ timeout_handler timeout_cb ;
13+ } Node , * pNode ;
14+
15+ typedef struct timing_wheel {
16+ int cur_slot ;
17+ int granularity ;
18+ Node nodes [WHEEL_BIN_NUMBER ];
19+ } TWheel , * pTWheel ;
20+
21+ pTWheel init_time_wheel (int gran ) {
22+ pTWheel new_wheel = (pTWheel ) malloc (sizeof (TWheel ));
23+ new_wheel -> granularity = gran ;
24+ new_wheel -> cur_slot = 0 ;
25+ int i ;
26+ for (i ; i < WHEEL_BIN_NUMBER ; i ++ ) {
27+ new_wheel -> nodes [i ].next = NULL ;
28+ }
29+
30+ return new_wheel ;
31+ }
32+
33+ int install_handler (pTWheel twheel , int deadline , timeout_handler new_cb ) {
34+ int ret = 0 ;
35+ if (deadline /twheel -> granularity >= WHEEL_BIN_NUMBER ) {
36+ printf ("Deadline exceed timing wheel size\n" );
37+ return -1 ;
38+ }
39+
40+ int index = (twheel -> cur_slot + ((deadline /(twheel -> granularity ))))%WHEEL_BIN_NUMBER ;
41+ pNode iterator = & (twheel -> nodes [index ]);
42+
43+ while (iterator -> next ) {
44+ iterator = iterator -> next ;
45+ }
46+
47+ pNode new_node = (pNode ) malloc (sizeof (Node ));
48+ new_node -> timeout_cb = new_cb ;
49+ new_node -> next = NULL ;
50+ iterator -> next = new_node ;
51+
52+ return ret ;
53+ }
54+
55+ void tick (pTWheel twheel ) {
56+ int i ;
57+ pNode iterator = & twheel -> nodes [twheel -> cur_slot ];
58+ while (iterator -> next ) {
59+ iterator -> next -> timeout_cb ();
60+ pNode tmp = iterator -> next ;
61+ iterator -> next = iterator -> next -> next ;
62+ free (tmp );
63+ }
64+ twheel -> cur_slot = (twheel -> cur_slot + 1 )%WHEEL_BIN_NUMBER ;
65+ }
66+
67+ void print_task () {
68+ printf ("Hi1\n" );
69+ }
70+
71+ void print_task2 () {
72+ printf ("Hi2\n" );
73+ }
74+
75+ void print_task3 () {
76+ printf ("Hi3\n" );
77+ }
78+
79+ int main (void ) {
80+ int ret = 0 ;
81+
82+ pTWheel new_wheel = init_time_wheel (GRANULARITY );
83+ timeout_handler cb1 = print_task ;
84+ install_handler (new_wheel , 4 * GRANULARITY , cb1 );
85+
86+ timeout_handler cb2 = print_task2 ;
87+ install_handler (new_wheel , 8 * GRANULARITY , cb2 );
88+
89+ timeout_handler cb3 = print_task3 ;
90+ install_handler (new_wheel , 8 * GRANULARITY , cb3 );
91+
92+ install_handler (new_wheel , 12 * GRANULARITY , cb3 );
93+
94+ int count = 0 ;
95+ while (count < 5 ) {
96+ tick (new_wheel );
97+ usleep (GRANULARITY );
98+ printf ("Time: %d\n" , count ++ );
99+ }
100+
101+ return 0 ;
102+ }
0 commit comments