c语言实现定时器时间轮

本代码是在根据内核中的时间轮代码进行改造 适用于应用层,若发现问题 欢迎指正

/*
 *毫秒定时器  采用多级时间轮方式  借鉴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 +
  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值