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
| #ifndef LST_TIMER #define LST_TIMER
#include <time.h> #define BUFFER_SIZE 64 class util_timer;
struct client_data { sockaddr_in address; int sockfd; char buf[BUFFER_SIZE]; util_timer* timer; };
class util_timer { public: util_timer() : prev(NULL), next(NULL){} time_t expire; void (*cb_func)(client_data*); client_data* user_data; util_timer* prev; util_timer* next; };
class sort_timer_lst { public: sort_timer_lst() : head(NULL), tail(NULL) {} ~sort_timer_lst() { util_timer* tmp = head; while (tmp) { head = tmp->next; delete tmp; tmp = head; } }
void add_timer(util_timer* timer) { if (!timer) { return; } if (!head) { head = tail = timer; return; }
if (timer->expire < head->expire) { timer->next = head; head->prev = timer; head = timer; return; } add_timer(timer, head); }
void adjust_timer(util_timer* timer) { if (!timer) { return; } util_timer* tmp = timer->next; if (!tmp || (timer->expire < tmp->expire)) { return; } if (timer == head) { head = head->next; head->prev = NULL; timer->next = NULL; add_timer(timer, head); } else { timer->prev->next = timer->next; timer->next->prev = timer->prev; add_timer(timer, timer->next); } }
void del_timer(util_timer* timer) { if (!timer) { return; } if ((timer == head) && (timer == tail)) { delete timer; head = NULL; tail = NULL; return; }
if (timer == head) { head = head->next; head->prev = NULL; delete timer; return; }
if (timer == tail) { tail = tail->prev; tail->next = NULL; delete timer; return; }
timer->prev->next = timer->next; timer->next->prev = timer->prev; delete timer; }
void tick() { if (!head) { return; } printf("timer tick\n"); time_t cur = time(NULL); util_timer* tmp = head;
while (tmp) { if (cur < tmp->expire) { break; } tmp->cb_func(tmp->user_data); head = tmp->next; if (head) { head->prev = NULL; } delete tmp; tmp = head; } } private: void add_timer(util_timer* timer, util_timer* lst_head) { util_timer* prev = lst_head; util_timer* tmp = prev->next; while (tmp) { if (timer->expire < tmp->expire) { prev->next = timer; timer->next = tmp; tmp->prev = timer; timer->prev = prev; break; } prev = tmp; tmp = tmp->next; }
if (!tmp) { prev->next = timer; timer->prev = prev; timer->next = NULL; tail = timer; } }
util_timer* head; util_timer* tail; };
#endif
|
此文件被包含在头文件中以便方便使用。tick为心跳函数,每隔一段时间执行一次。判断任务到期为定时器expire参数小于当前系统时间。
执行时间复杂度:
添加O(n),删除O(1),执行任务O(1)
reference:
Linux高性能服务器编程——游双