## 1. 多级时间轮定时器架构设计 ### 1.1 系统工作原理 多级时间轮采用类似机械钟表的级联结构由5个不同精度的时间轮组成 - 第1级工作轮256个槽位TVR_SIZE精度1ms - 第2-5级各64个槽位TVN_SIZE 级联机制表现为 1. 当低级轮完成完整周期如TV1转完256ms 2. 触发高一级轮前进一个槽位TV2移动1格 3. 高级轮当前槽位的任务重新分配到低级轮 c #define TVR_BITS 8 // 第一级8位(256) #define TVN_BITS 6 // 其他级6位(64)1.2 核心数据结构时间轮基座(tvec_base)struct tvec_base { unsigned long current_index; // 当前时间戳 pthread_t thincrejiffies; // 时间推进线程 struct tvec_root tv1; // 第一级轮 struct tvec tv2[4]; // 2-5级轮 };定时任务对象(timer_list)struct timer_list { struct list_head entry; // 双向链表节点 unsigned long expires; // 到期时间戳 void (*function)(unsigned long); // 回调函数 unsigned long data; // 回调参数 struct tvec_base *base; // 所属时间轮 };2. 关键实现技术2.1 时间轮初始化创建五级时间轮时需要初始化每个轮子的槽位链表启动独立线程处理时间推进void init_tvr_list(struct tvec_root *tvr) { for(int i0; iTVR_SIZE; i) INIT_LIST_HEAD(tvr-vec[i]); }2.2 任务添加算法根据时间差决定任务放置的轮级void internal_add_timer(struct tvec_base *base, struct timer_list *timer) { unsigned long idx timer-expires - base-current_index; if(idx TVR_SIZE) { // 第1级 int i expires TVR_MASK; vec base-tv1.vec i; } else if(idx 1(TVR_BITSTVN_BITS)) { // 第2级 int i (expires TVR_BITS) TVN_MASK; vec base-tv2.vec i; } // ...其他级类似 list_add_tail(timer-entry, vec); }2.3 级联迁移机制当工作轮完成周期时触发级联int cascade(struct tvec_base *base, struct tvec *tv, int index) { list_replace_init(tv-vec index, tv_list); list_for_each_safe(pos, tmp, tv_list) { timer list_entry(pos, struct timer_list, entry); internal_add_timer(base, timer); // 重新分配 } return index; }3. 性能优化策略3.1 位运算加速利用位操作快速计算槽位#define INDEX(N) ((base-current_index (TVR_BITS (N)*TVN_BITS)) TVN_MASK)3.2 双向链表优化采用Linux内核风格的list_head结构struct list_head { struct list_head *next, *prev; }; #define list_for_each_safe(pos, n, head) \ for(pos(head)-next, npos-next; pos!(head); posn, npos-next)4. 应用示例4.1 创建周期性定时器void mytimer(unsigned long arg) { struct request_para *para (struct request_para *)arg; log(%d, para-val); mod_timer(para-timer, 3000); // 重新激活 } int main() { void *wheel ti_timewheel_create(); struct request_para *para malloc(sizeof(*para)); para-timer ti_add_timer(wheel, 3000, mytimer, (unsigned long)para); while(1) sleep(2); }4.2 定时精度测试实测输出间隔[DEBUG] mytimer:370]: 100 // 每3秒精确触发5. 设计局限与改进方向阻塞问题耗时任务会阻塞后续定时触发解决方案将任务放入线程池执行时间跨度最大约49天2^32 ms可扩展为6级时间轮支持更长间隔精度限制依赖系统时钟精度建议结合高精度定时器如timerfd// 改进方案示例非阻塞执行 void mytimer(unsigned long arg) { pthread_create(worker, NULL, async_task, (void*)arg); }