linux 定时器(c++)(2)时间轮

节点类
相比较时间升序链表中的绝对时间expire

tw_timer采用的是相对时间的概念也就多出
rotation ,time_slot俩属性,rotation是转的“圈数”,time_slot是转到时间轮的哪一块区域。好比现在在1:05,过了65分钟时针走了闹钟的1rotation并走到10 time_slot;

tw_timer.h

//
// Created by adl on 2020/7/22.
//

#ifndef TEST2_TW_TIMER_H
#define TEST2_TW_TIMER_H

class client_data ;
class tw_timer {
   
public:
    tw_timer(int rot,int ts);

public:
    int rotation;
    int time_slot;
    void(*cb_func)(client_data*);
    client_data*user_data;
    tw_timer*next;
    tw_timer*prev;
};



#endif //TEST2_TW_TIMER_H

tw_timer.cpp

//
// Created by adl on 2020/7/22.
//

#include "tw_timer.h"

tw_timer::tw_timer(int rot, int ts) :next(nullptr),prev(nullptr),rotation(rot),time_slot(ts){
   

}

client_data.h

//
// Created by adl on 2020/7/22.
//

#ifndef TEST2_CLIENT_DATA_H
#define TEST2_CLIENT_DATA_H

#include <sys/socket.h>
#include <netinet/in.h>

#include <sys/epoll.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <libgen.h>
#include <stdlib.h>
#include <errno.h>

#define BUFFER_SIZE 64

//class util_timer;

class tw_timer;
//class heap_timer;
struct client_data {
   
    sockaddr_in address;
    int sockfd;
    char buf[BUFFER_SIZE];
    union {
   
        tw_timer *timer;
//        util_timer *timer;
//        heap_timer*timer3;
    };
};

#endif //TEST2_CLIENT_DATA_H

time_wheel.cpp
可以注意到这个时间轮类的接口和时间升序链表的接口基本一致

//
// Created by adl on 2020/7/22.
//

#ifndef TEST2_TIME_WHEEL_H
#define TEST2_TIME_WHEEL_H

class tw_timer;

class time_wheel {
   
public:
    time_wheel();

    virtual ~time_wheel();

    tw_timer *add_timer(int timeout);

    void del_timer(tw_timer *timer);

    void tick();
    tw_timer *adjust_timer(tw_timer *timer, int timeout);

private:
    static const int N= 60;//一圈60块区域
    static const int SI =1;//SI可以想象成时针或者分钟每次转动的幅度
    tw_timer*slots[N];
    int cur_slot;//当前所在区域

};

#endif //TEST2_TIME_WHEEL_H

time_wheel.cpp

//
// Created by adl on 2020/7/22.
//

#include <cstdio>
#include "time_wheel.h"
#include "tw_timer.h"

time_wheel::~time_wheel() {
   
    for (int i = 0; i < N; ++i) {
   
        tw_timer *tmp = slots[i];
        while (tmp) {
   
            slots[i] = tmp->next;
            delete tmp;
            tmp = slots[i];
        }
    }
}

time_wheel::time_wheel() : cur_slot(0) {
   
    for (int i = 0; i < N; ++i) {
   
        slots[i] = nullptr;
    }
}

tw_timer *time_wheel::add_timer(int timeout) {
   
    if (timeout < 0) {
   
        return nullptr;
    }
    int ticks = 0;
    if (timeout < SI) 
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值