本代码是在根据内核中的时间轮代码进行改造 适用于应用层,若发现问题 欢迎指正
/*
*毫秒定时器 采用多级时间轮方式 借鉴linux内核中的实现
*支持的范围为1 ~ 2^32 毫秒(大约有49天)
*若设置的定时器超过最大值 则按最大值设置定时器
**/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/time.h>
#include "list.h"
#define TVN_BITS 6
#define TVR_BITS 8
#define TVN_SIZE (1<<TVN_BITS)
#define TVR_SIZE (1<<TVR_BITS)
#define TVN_MASK (TVN_SIZE - 1)
#define TVR_MASK (TVR_SIZE - 1)
#define SEC_VALUE 0
#define USEC_VALUE 2000
struct tvec_base;
#define INDEX(N) ((ba->current_index >> (TVR_BITS + (N) * TVN_BITS)) & TVN_MASK)
typedef void (*timeouthandle)(unsigned long );
struct timer_list{
struct list_head entry; //将时间连接成链表
unsigned long expires; //超时时间
void (*function)(unsigned long); //超时后的处理函数
unsigned long data; //处理函数的参数
struct tvec_base *base; //指向时间轮
};
struct tvec {
struct list_head vec[TVN_SIZE];
};
struct tvec_root{
struct list_head vec[TVR_SIZE];
};
//实现5级时间轮 范围为0~ (2^8 * 2^6 * 2^6 * 2^6 *2^6)=2^32
struct tvec_base
{
unsigned long current_index;
pthread_t thincrejiffies;
pthread_t thdealfun;
struct tvec_root tv1;
struct tvec tv2;
struct tvec tv3;
struct tvec tv4;
struct tvec tv5;
};
static void internal_add_timer(struct tvec_base *base, struct timer_list *timer)
{
struct list_head *vec;
unsigned long expires = timer->expires;
unsigned long idx = expires - base->current_index;
if ( idx < TVR_SIZE )
{
int i = expires & TVR_MASK;
vec = base->tv1.vec + i;
}
else if( idx < 1 << (TVR_BITS + TVN_BITS) )
{
int i = (expires >> TVR_BITS) & TVN_MASK;
vec = base->tv2.vec + i;
}
else if( idx < 1 << (TVR_BITS +