层级时间轮 | skynet 定时器
skynet定时器
要解析一个程序代码,先了解数据结构,这是基础,再看函数。 拿skynet定时器举例子。
数据结构
//定时器事件 用于抛出定时器事件到消息队列里。理解这个数据结构需要先了解skynet的框架原理,
//不理解这个数据结构也不影响下面的论述
struct timer_event {
int32_t handle;
int session;
};
//定时器节点
struct timer_node {
struct timer_node *next;
uint32_t expire;
};
//定时器链表
struct link_list {
struct timer_node head;
struct timer_node *tail;
};
//层级时间轮
//存放所有定时器的地方
struct timer {
struct link_list near[TIME_NEAR]; //最近的定时器
struct link_list t[4][TIME_LEVEL];//更久远的定时器
struct spinlock lock; //全局锁
uint32_t time; //当前滴答数
uint32_t starttime; //程序开始时间 绝对时间 时间戳,单位 s 秒
uint64_t current; //当前时间 相对时间 1cs 厘秒 = 10ms 毫秒
uint64_t current_point; //系统(pc)运行时间 相对时间 单位: cs 厘秒
};
上面定时器的基本数据结构了解了,再来看下面的函数, 基本思路是一样的。
……