skynet源码分析(7)--skynet中的timer

作者:shihuaping0918@163.com,转载请注明作者
skynet的timer是做游戏用得比较频繁的一个功能,分析一下它的源码还是有意义的。而且核心的C源码除了timer和网络以外,已经基本分析得差不多了。其它都是跟lua c api相关,或者是跟lua交互比较多的。timer的源码在skynet-timer.c和skynet-timer.h中。


在开始看代码之前,请大家默念三遍:
1秒=1000毫秒
1毫秒=1000微秒
1微秒=1000纳秒


然后再默念三遍:
skynet中的时间精度是10ms级别。


如果念完了我们开始准备看代码,在看源码前,还要说明一下,skynet的外部定时器是分为两部分存的,一部分存在叫near的数组里,另一部分存在一个二维数组里,分为四个级别。


最后,如果对位运算不熟悉的话就请回吧。


```
typedef void (*timer_execute_func)(void *ud,void *arg);


#define TIME_NEAR_SHIFT 8
#define TIME_NEAR (1 << TIME_NEAR_SHIFT)
#define TIME_LEVEL_SHIFT 6
#define TIME_LEVEL (1 << TIME_LEVEL_SHIFT)
#define TIME_NEAR_MASK (TIME_NEAR-1)
#define TIME_LEVEL_MASK (TIME_LEVEL-1)


//先搞清楚下面的单位
//1秒=1000毫秒 milliseconds
//1毫秒=1000微秒 microseconds
//1微秒=1000纳秒 nanoseconds


//整个timer中毫秒的精度都是10ms,
//也就是说毫秒的一个三个位,但是最小的位被丢弃


struct timer_event {
uint32_t handle; //即是设置定时器的来源,又是超时消息发送的目标
int session; //session,一个增ID,溢出了从1开始,所以不要设时间很长的timer
};


//链表
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; //程序启动的时间点,timestamp,秒数
uint64_t current; //从程序启动到现在的耗时,精度10毫秒级
uint64_t current_point; //当前时间,精度10毫秒级
};


static struct timer * TI = NULL;


//清空链表,返回链表第一个结点
static inline struct timer_node *
link_clear(struct link_list *list) {
struct timer_node * ret = list->head.next;
list->head.next = 0;
list->tail = &(list->head);


return ret;
}


//将结点放入链表
static inline void
link(struct link_list *list,struct timer_node *node) {
list->tail->next = node;
list->tail = node;
node->next=0;
}


//添加一个定时器结点
static void
add_node(struct timer *T,struct timer_node *node) {
uint32_t time=node->expire; //去看一下它是在哪赋值的
uint32_t current_time=T->time; //当前计数
//没有超时,或者说时间点特别近了
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值