Linux提供了三种定时方法:

  1. socket读写超时选项:SO_RCVTIMEO和SO_SNDTIMEO
  2. IO复用API中的timeout参数
  3. Linux提供的定时函数和计时函数,比如:
    1. 由alarm函数和settimer函数设置的超时闹钟,触发SIGALRM信号
    2. timefd_系列函数处理定时任务

      1 SO_RCVTIMEO和SO_SNDTIMEO

      通过setsockopt函数可以设置socket相关的API函数的收发超时时间。对于不同的API函数,超时返回的errno如下:
系统调用 有效选项 函数超时后的行为
send SO_SNDTIMEO 返回-1,errno为EAGAIN、EWOULDBLOCK
sendmsg SO_SNDTIMEO 返回-1,errno为EAGAIN、EWOULDBLOCK
recv SO_RCVTIMEO 返回-1,errno为EAGAIN、EWOULDBLOCK
recvmsg SO_RCVTIMEO 返回-1,errno为EAGAIN、EWOULDBLOCK
accept SO_RCVTIMEO 返回-1,errno为EAGAIN、EWOULDBLOCK
connect SO_SNDTIMEO 返回-1,errno为EINPROGRESS

在程序中,我们可以根据每个函数的返回值和errno判断是否超时。

connect超时的示例:

  1. //模拟客户端connect超时
  2. #include <sys/types.h>
  3. #include <sys/socket.h>
  4. #include <netinet/in.h>
  5. #include <arpa/inet.h>
  6. #include <assert.h>
  7. #include <stdio.h>
  8. #include <unistd.h>
  9. #include <errno.h>
  10. #include <string.h>
  11. #include <fcntl.h>
  12. #include <stdlib.h>
  13. #include <sys/epoll.h>
  14. #include <stdbool.h>
  15. #include <libgen.h>
  16. int main(int argc, char *argv[])
  17. {
  18. if (argc <= 2)
  19. {
  20. printf("Usage: %s ip_address port_number\n", basename(argv[0]));
  21. return 1;
  22. }
  23. const char *ip = argv[1];
  24. const int port = atoi(argv[2]);
  25. int ret = 0;
  26. struct sockaddr_in address;
  27. bzero(&address, sizeof(address));
  28. address.sin_family = AF_INET; //IPv4
  29. address.sin_addr.s_addr = inet_addr(ip);
  30. address.sin_port = htons(port);
  31. int listenfd = socket(PF_INET, SOCK_STREAM, 0);
  32. assert(listenfd >= 0);
  33. //设置socket选项,配置可写超时
  34. struct timeval timeout;
  35. timeout.tv_sec = 10; //10s
  36. timeout.tv_usec = 0;
  37. ret = setsockopt(listenfd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
  38. assert(ret >= 0);
  39. ret = connect(listenfd, (struct sockaddr*)&address, sizeof(address));
  40. if (ret == -1)
  41. {
  42. //返回-1,errno为EINPROGRESS,则表示connect超时
  43. if (errno = EINPROGRESS)
  44. {
  45. printf("connecting timeout, process timeout logic\n");
  46. }
  47. else
  48. {
  49. printf("error occur when connecting to server\n");
  50. }
  51. }
  52. close(listenfd);
  53. return 0;
  54. }

2 IO复用函数的超时参数

select、poll和epoll函数都带有超时参数,所以它们也能统一处理定时事件。
由于函数可能在超时之前就返回,所以需要不断的更新定时参数以反映剩余的时间,如下:

  1. #define TIMEOUT 5000
  2. int timeout = TIMEOUT;
  3. time_t start = time(NULL);
  4. time_t end = time(NULL);
  5. while(1)
  6. {
  7. printf("the timeout is now %d ml-seconds\n", timeout);
  8. start = time(NULL);
  9. //指定timeout参数
  10. int number = epoll_wait(epollfd, events, MAX_EVENT_NUMBER, timeout);
  11. if (number < 0 && errno != EINTR)
  12. {
  13. printf("epoll failed\n");
  14. break;
  15. }
  16. if (number = 0)//返回0,说明超时时间到了,没有监听的事件发生
  17. {
  18. timeout = TIMEOUT;//重置定时时间
  19. continue;
  20. }
  21. end = time(NULL);
  22. //如果number>0,说明监听的事件发生,没有超时,需要计算剩余时间
  23. timeout -= (end - start) / 1000;
  24. if (timeout <= 0)//剩余时间不够,重置时间
  25. {
  26. timeout = TIMEOUT;
  27. }
  28. //do somethings
  29. }

3 Linux定时函数

3.1 SIGALRM信号

一般而言,SIGALRM信号按照固定的频率生成,即有alarm或setitimer函数设置的定时周期T保持不变。如果某个定时任务的超时时间不是T的整数倍,那么它实际被执行的时间和预期的时间将略有偏差,因此定时周期T反映了定时的精度
在多线程中处理信号是很麻烦的事,所以应该尽量避免使用触发信号的方式

  1. int setitimer(int which, const struct itimerval *new_value, struct itimerval *old_value);
  2. //结构体定义如下:
  3. struct itimerval {
  4. struct timeval it_interval; /* Interval for periodic timer */
  5. struct timeval it_value; /* Time until next expiration */
  6. };
  7. unsigned int alarm(unsigned int seconds);

3.2 timefd_系列函数

陈硕在muduo的书中提到,对于定时任务,应该采取如下原则:

  • 计时:只使用gettimeofday来获取当前时间
  • 定时:只使用timerfd_*系列函数来处理定时任务
    • timerfd_create把时间变成了一个文件描述符,该“文件”在定时器超时的那一刻变得可读,这样就能很方便地融入select(2)/poll(2)框架中,用统一的方式来处理IO事件和超时事件。
    • IO复用函数自带的timeout参数精度是毫秒,而timerfd_setime的精度可以达到纳秒

函数定义如下:

  1. int gettimeofday(struct timeval *tv, struct timezone *tz);
  2. int timerfd_create(int clockid, int flags);
  3. int timerfd_settime(int fd, int flags,
  4. const struct itimerspec *new_value,
  5. struct itimerspec *old_value);
  6. int timerfd_gettime(int fd, struct itimerspec *curr_value);

4 两种高性能定时器设计

4.1 时间轮

image.png
在时间轮中:

  • 实线指针指向轮子上的一个槽(slot)。它以恒定的速度顺时针转动,每转动一步就指向下一个槽(slot)。每次转动称为一个滴答(tick),一个tick时间间隔为时间轮的si(slot interval)。该时间轮共有N个槽,因此它转动一周的时间是N*si
  • 每个槽指向一条定时器链表,每条链表上的定时器具有相同的特征:它们的定时时间相差N*si的整数倍。时间轮正是利用这个关系将定时器散列到不同的链表中
  • 假如现在指针指向槽cs,我们要添加一个定时时间为ti的定时器,则该定时器将被插入槽ts(timer slot)对应的链表中:ts=(cs + (ti / si)) % N

时间轮使用了哈希表处理冲突的思想,将定时器散列到不同的链表上。这样每条链表上的定时器数目都将明显少于原来的排序链表上的定时器数目,插入操作的效率基本不受定时器数目的影响。对于时间轮而言,要提高精度,就要使si的值足够小; 要提高执行效率,则要求N值足够大,使定时器尽可能的分布在不同的槽
对于时间轮,添加、删除和执行一个定时器的时间复杂度都是O(1)。
**
简单的一层时间轮设计示例:

  1. #ifndef TIME_WHEEL_TIMER
  2. #define TIME_WHEEL_TIMER
  3. #include <time.h>
  4. #include <netinet/in.h>
  5. #include <stdio.h>
  6. #define BUFFER_SIZE 64
  7. class tw_timer;
  8. struct client_data //绑定socket和定时器
  9. {
  10. sockaddr_in address;
  11. int sockfd;
  12. char buf[BUFFER_SIZE];
  13. tw_timer *timer;
  14. };
  15. class tw_timer //定时器类
  16. {
  17. public:
  18. tw_timer(int rot, int ts)
  19. : next(NULL), prev(NULL), rotation(rot), time_slot(ts) {}
  20. public:
  21. int rotation; //记录该定时器在时间轮转多少圈后生效
  22. int time_slot; //记录定时器属于那个槽
  23. void (*cb_func)(client_data *); //定时器回调函数
  24. client_data *user_data; //用户数据
  25. tw_timer *next; //指向上一个定时器
  26. tw_timer *prev; //指向下一个定时器
  27. };
  28. class time_wheel //事件轮管理定时器
  29. {
  30. public:
  31. time_wheel() : cur_slot(0)
  32. {
  33. for (int i = 0; i < N; ++i)
  34. {
  35. slots[i] = NULL; //每个槽的头节点初始化为空
  36. }
  37. }
  38. ~time_wheel()
  39. {
  40. for (int i = 0; i < N; ++i)
  41. {
  42. tw_timer *tmp = slots[i];
  43. while (tmp)
  44. {
  45. slots[i] = tmp->next;
  46. delete tmp; //遍历每个槽,销毁new分配在堆中的定时器
  47. tmp = slots[i];
  48. }
  49. }
  50. }
  51. tw_timer *add_timer(int timeout) //添加新的定时器,插入到合适的槽中
  52. {
  53. if (timeout < 0) //时间错误
  54. {
  55. return NULL;
  56. }
  57. int ticks = 0;
  58. if (timeout < TI) //小于每个槽的interval,则为1
  59. {
  60. ticks = 1;
  61. }
  62. else
  63. {
  64. ticks = timeout / TI; //相对当前位置的槽数
  65. }
  66. int rotation = ticks / N; //记录多少圈后生效
  67. int ts = (cur_slot + (ticks % N)) % N; //确定插入槽的位置
  68. tw_timer *timer = new tw_timer(rotation, ts); //根据位置和圈数,插入对应的槽中
  69. if (!slots[ts]) //所在槽头节点为空,直接插入
  70. {
  71. printf("add timer, rotation is %d, ts is %d, cur_slot is %d\n", rotation, ts, cur_slot);
  72. slots[ts] = timer;
  73. }
  74. else //头插法
  75. {
  76. timer->next = slots[ts];
  77. slots[ts]->prev = timer;
  78. slots[ts] = timer;
  79. }
  80. return timer; //返回含有时间信息和所在槽位置的定时器
  81. }
  82. void del_timer(tw_timer *timer) //从时间轮上删除定时器
  83. {
  84. if (!timer)
  85. {
  86. return;
  87. }
  88. int ts = timer->time_slot; //找到所在槽
  89. if (timer == slots[ts])
  90. {
  91. slots[ts] = slots[ts]->next;
  92. if (slots[ts])
  93. {
  94. slots[ts]->prev = NULL;
  95. }
  96. delete timer;
  97. }
  98. else
  99. {
  100. timer->prev->next = timer->next;
  101. if (timer->next)
  102. {
  103. timer->next->prev = timer->prev;
  104. }
  105. delete timer;
  106. }
  107. }
  108. void tick()
  109. {
  110. tw_timer *tmp = slots[cur_slot]; //取出当前槽的头节点
  111. printf("current slot is %d\n", cur_slot);
  112. while (tmp) //遍历
  113. {
  114. printf("tick the timer once\n");
  115. if (tmp->rotation > 0)
  116. {
  117. tmp->rotation--;
  118. tmp = tmp->next;
  119. }
  120. else
  121. {
  122. tmp->cb_func(tmp->user_data); //符合条件,调用回调函数
  123. if (tmp == slots[cur_slot])
  124. {
  125. printf("delete header in cur_slot\n");
  126. slots[cur_slot] = tmp->next;
  127. delete tmp;
  128. if (slots[cur_slot])
  129. {
  130. slots[cur_slot]->prev = NULL;
  131. }
  132. tmp = slots[cur_slot];
  133. }
  134. else
  135. {
  136. tmp->prev->next = tmp->next;
  137. if (tmp->next)
  138. {
  139. tmp->next->prev = tmp->prev;
  140. }
  141. tw_timer *tmp2 = tmp->next;
  142. delete tmp;
  143. tmp = tmp2;
  144. }
  145. }
  146. }
  147. cur_slot = ++cur_slot % N;
  148. }
  149. private:
  150. static const int N = 60;
  151. static const int TI = 1;
  152. tw_timer *slots[N];
  153. int cur_slot;
  154. };
  155. #endif

4.2 时间堆

时间轮方案都是以固定的频率调用心搏函数tick,并在其中依次检测到期的定时器,然后执行到期定时器上的回调函数
设计定时器的另外一种思路是:将所有定时器中超时时间最小的一个定时器的超时值作为心搏间隔。这样,一旦心搏函数tick被调用,超时时间最小的定时器必然到期,我们就可以在tick函数中处理该定时器。然后,再次从剩余的定时器中找出超时时间最小的一个,并将这段最小时间设置为下一次心搏间隔。如此反复, 就可以使用最小堆(每个节点都小于等于其子节点)实现了较为精确的定时。

对于时间堆,添加一个定时器的时间复杂度为O(lgn),删除和执行一个定时器的时间复杂度为O(1)。

实现示例:

  1. #ifndef intIME_HEAP
  2. #define intIME_HEAP
  3. #include <iostream>
  4. #include <netinet/in.h>
  5. #include <time.h>
  6. using std::exception;
  7. #define BUFFER_SIZE 64
  8. class heap_timer;
  9. struct client_data
  10. {
  11. sockaddr_in address;
  12. int sockfd;
  13. char buf[BUFFER_SIZE];
  14. heap_timer *timer;
  15. };
  16. class heap_timer
  17. {
  18. public:
  19. heap_timer(int delay)
  20. {
  21. expire = time(NULL) + delay;
  22. }
  23. public:
  24. time_t expire; //定时器生效的绝对时间
  25. void (*cb_func)(client_data *); //定时器回调函数
  26. client_data *user_data; //用户数据
  27. };
  28. class time_heap //时间堆类
  29. {
  30. public:
  31. time_heap(int cap) throw(std::exception)
  32. : capacity(cap), cur_size(0)//构造函数,初始化空堆
  33. {
  34. array = new heap_timer *[capacity];
  35. if (!array)
  36. {
  37. throw std::exception();
  38. }
  39. for (int i = 0; i < capacity; ++i)
  40. {
  41. array[i] = NULL;
  42. }
  43. }
  44. time_heap(heap_timer **init_array, int size, int capacity) throw(std::exception)
  45. : cur_size(size), capacity(capacity)//构造函数,有init_array初始化堆
  46. {
  47. if (capacity < size)
  48. {
  49. throw std::exception();
  50. }
  51. array = new heap_timer *[capacity];
  52. if (!array)
  53. {
  54. throw std::exception();
  55. }
  56. for (int i = 0; i < capacity; ++i)
  57. {
  58. array[i] = NULL;
  59. }
  60. if (size != 0)
  61. {
  62. for (int i = 0; i < size; ++i)
  63. {
  64. array[i] = init_array[i];
  65. }
  66. for (int i = (cur_size - 1) / 2; i >= 0; --i)
  67. {
  68. percolate_down(i);
  69. }
  70. }
  71. }
  72. ~time_heap()
  73. {
  74. for (int i = 0; i < cur_size; ++i)
  75. {
  76. delete array[i];
  77. }
  78. delete[] array;
  79. }
  80. public:
  81. void add_timer(heap_timer *timer) throw(std::exception)
  82. {
  83. if (!timer)
  84. {
  85. return;
  86. }
  87. if (cur_size >= capacity)
  88. {
  89. resize();//当前堆容量不够,扩大一倍容量
  90. }
  91. int hole = cur_size++;
  92. int parent = 0;
  93. for (; hole > 0; hole = parent)
  94. {
  95. parent = (hole - 1) / 2;
  96. if (array[parent]->expire <= timer->expire)
  97. {
  98. break;
  99. }
  100. array[hole] = array[parent];
  101. }
  102. array[hole] = timer;
  103. }
  104. void del_timer(heap_timer *timer)
  105. {
  106. if (!timer)
  107. {
  108. return;
  109. }
  110. //设置回调函数为空,节省了真正删除定时器构成的开销,但缺点是容易使堆数组膨胀
  111. timer->cb_func = NULL;
  112. }
  113. heap_timer *top() const
  114. {
  115. if (empty())
  116. {
  117. return NULL;
  118. }
  119. return array[0];
  120. }
  121. void pop_timer()
  122. {
  123. if (empty())
  124. {
  125. return;
  126. }
  127. if (array[0])
  128. {
  129. delete array[0];
  130. array[0] = array[--cur_size];
  131. percolate_down(0);
  132. }
  133. }
  134. void tick()
  135. {
  136. heap_timer *tmp = array[0];
  137. time_t cur = time(NULL);
  138. while (!empty())
  139. {
  140. if (!tmp)
  141. {
  142. break;
  143. }
  144. if (tmp->expire > cur)
  145. {
  146. break;
  147. }
  148. if (array[0]->cb_func)//array[0]使最小的超时时间,执行其回调函数
  149. {
  150. array[0]->cb_func(array[0]->user_data);
  151. }
  152. pop_timer();//删除堆顶节点,生成新的顶节点
  153. tmp = array[0];
  154. }
  155. }
  156. bool empty() const { return cur_size == 0; }
  157. private:
  158. void percolate_down(int hole)
  159. {
  160. heap_timer *temp = array[hole];
  161. int child = 0;
  162. for (; ((hole * 2 + 1) <= (cur_size - 1)); hole = child)
  163. {
  164. child = hole * 2 + 1;
  165. if ((child < (cur_size - 1)) && (array[child + 1]->expire < array[child]->expire))
  166. {
  167. ++child;
  168. }
  169. if (array[child]->expire < temp->expire)
  170. {
  171. array[hole] = array[child];
  172. }
  173. else
  174. {
  175. break;
  176. }
  177. }
  178. array[hole] = temp;
  179. }
  180. void resize() throw(std::exception)
  181. {
  182. heap_timer **temp = new heap_timer *[2 * capacity];
  183. for (int i = 0; i < 2 * capacity; ++i)
  184. {
  185. temp[i] = NULL;
  186. }
  187. if (!temp)
  188. {
  189. throw std::exception();
  190. }
  191. capacity = 2 * capacity;
  192. for (int i = 0; i < cur_size; ++i)
  193. {
  194. temp[i] = array[i];
  195. }
  196. delete[] array;
  197. array = temp;
  198. }
  199. private:
  200. heap_timer **array; //堆数组
  201. int capacity; //堆容量
  202. int cur_size; //当前元素个数
  203. };
  204. #endif