节点类
相比较时间升序链表中的绝对时间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)