上次说到,基于排序链表的定时器存在一个问题:添加定时器的效率偏低。这次我们用时间轮来解决该问题。
如图就是一个时间轮:
在时间轮内,指针指向轮子上的一个槽。它以恒定的速率顺时针转动。没转动一步就指向下一个槽,每次转动称之为一个tick。一个滴答的时间称为时间轮的槽间隔si(slot interval),它实际上就是心搏时间。时间轮共有N个槽,因此它运转一周的时间是N*si。每个槽指向一个定时器链表,每条链表上的定时器具有相同的特征:它们的定时时间相差N*si的整数倍。时间轮正式利用这个关系将定时器散列到不同的链表中。加入现在指针指向槽cs,我们要添加一个定时时间为ti的定时器,则该定时器将被插入槽ts(timer slot)对应的链表中:
ts = (cs + (ti / si)) % N
基于排序链表的定时器使用唯一的链表来管理所有定时器,所以插入操作的效率随着定时器数目的增多而降低。而时间轮使用哈希表的思想,将定时器散列到不同的链表上。这样每条链表上的定时器数目都将明显少于原来的排序链表上的定时器数目,插入操作的效率基本不受定时器数目的影响。
很显然,对时间轮而言,要提高定时精度,就要使si值足够小;要提高执行效率,则要求N值足够大。
上图描述的是一个简单的时间轮,仅仅一个轮子。而复杂的时间轮可能有多个轮子,不同轮子拥有不同的粒度。
下面是一个简单时间轮的实现代码:
#ifndef TIME_WHEEL_TIMER_H
#define TIME_WHEEL_TIMER_H
#include <time.h>
#include <netinet/in.h>
#include <stdio.h>
#include <assert.h>
const int BUFFER_SIZE = 1024;
class tw_timer;
//绑定socket和定时器
struct client_data {
sockaddr_in addr_;
int sockfd_;
char buf_[BUFFER_SIZE];
tw_timer* timer_;
};
//定时器类
class tw_timer {
public:
tw_timer(int rot, int ts)
: next_(NULL), prev_(NULL), rotation_(rot), time_slot_(ts)
{}
public:
void (*timeout_callback_)(client_data*); //定时器回调函数
public:
int rotation_; //记录定时器在时间轮转多少圈后生效,因为有的定时值比较大
int time_slot_; //记录定时器对应于时间轮上的哪个槽(对应的链表)
client_data *user_data_; //客户数据
tw_timer* next_; //指向上一个定时器
tw_timer* prev_; //指向下一个定时器
};
class time_wheel {
public:
time_wheel() : cur_slot_(0) {
memset(slots_, 0, sizeof(slots_)); //清零每个槽指针
}
~time_wheel(){
//遍历每个槽,并销毁其中的定时器
for(int i=0; i<DEFAULT_SLOTS_NUM; ++i){
tw_timer* tmp = slots_[i];
while(tmp != NULL){
slots_[i] = tmp->next_;
delete tmp;
tmp = slots_[i];
}
}
}
public:
tw_timer* add_timer(int timeout);
tw_timer* adjust_timer(tw_timer* timer, int timeout);
void del_timer(tw_timer* timer);
void tick();
private:
static const int DEFAULT_SLOTS_NUM = 60;
static const int SI = 1;
tw_timer* slots_[DEFAULT_SLOTS_NUM];
int cur_slot_;
};
//根据定时值timeout创建一个定时器,并把它插入合适的槽中
tw_timer* time_wheel::add_timer(int timeout)
{
if(timeout < 0)
return NULL;
//下面根据待插入定时器的超时值计算它将在时间轮转动多少个滴答后被触发,并将该滴答数存储于变量ticks中。
//如果待插入定时器的超时值小于时间轮的槽间隔SI,则将ticks折合为1,下一次它就被触发。否则将ticks向下折合为timeout/SI
int ticks = 0;
if(timeout < SI)
ticks = 1;
else
ticks = timeout / SI;
//计算待插入定时器在时间轮转多少圈后被触发
int rotation = ticks / DEFAULT_SLOTS_NUM;
//计算待插入的定时器应该被插入哪个槽中
int ts = (cur_slot_ + (ticks % DEFAULT_SLOTS_NUM)) % DEFAULT_SLOTS_NUM;
//创建新的定时器,它在时间轮转动rotation圈之后被触发,且位于第ts个槽上
tw_timer* timer = new tw_timer(rotation, ts);
//如果第ts个槽中无任何定时器,则把新建的定时器插入其中,并将该定时器设置为该槽的头结点
if(slots_[ts] == NULL){
printf("add timer, rotation is %d, ts is %d, cur_slot_ is %d\n", rotation, ts, cur_slot_);
slots_[ts] = timer;
}
else{ //否则,将定时器插入第ts个槽中
timer->next_ = slots_[ts];
slots_[ts]->prev_ = timer;
slots_[ts] = timer;
}
return timer;
}
//调整定时器,延长寿命
tw_timer* time_wheel::adjust_timer(tw_timer* timer, int timeout)
{
assert(timer != NULL && timeout >= 0);
printf("adjust timer\n");
del_timer(timer); //延长寿命我们需要删掉之前的,从新添加一个新的
return add_timer(timeout);
}
//删除目标定时器timer
void time_wheel::del_timer(tw_timer* timer)
{
if(timer == NULL)
return ;
int ts = timer->time_slot_;
//slots_[ts]是目标定时器所在槽的头结点。如果目标定时器就是该头结点,则需要重置第ts个槽的头结点
if(timer == slots_[ts]){
slots_[ts] = slots_[ts]->next_;
if(slots_[ts] != NULL)
slots_[ts]->prev_ = NULL;
delete timer;
}
else{
timer->prev_->next_ = timer->next_;
if(timer->next_ != NULL){
timer->next_->prev_ = timer->prev_;
}
delete timer;
}
}
//SI时间到后,调用该函数,先检验时间轮对应的槽的所有timer是否到期了,进行相应的处理。然后时间轮向前滚动一个槽的间隔。
void time_wheel::tick()
{
tw_timer* tmp = slots_[cur_slot_]; //取得时间轮上当前槽的头结点
printf("current slot is %d\n", cur_slot_);
while(tmp != NULL){
printf("tick the timer once\n");
//如果定时器的rotation值大于0,则它在这一轮补齐作用,它寿命还长着呢
if(tmp->rotation_ > 0){
tmp->rotation_--;
tmp = tmp->next_; //继续查找下一个timer
}
else{ //否则,说明定时器已经到期,于是执行定时任务,然后删除该定时器
tmp->timeout_callback_(tmp->user_data_);
if(tmp == slots_[cur_slot_]){
printf("delete header in cur_slot\n");
slots_[cur_slot_] = tmp->next_;
delete tmp;
if(slots_[cur_slot_] != NULL)
slots_[cur_slot_]->prev_ == NULL;
tmp = slots_[cur_slot_];
}
else{
tmp->prev_->next_ = tmp->next_;
if(tmp->next_ != NULL)
tmp->next_->prev_ = tmp->prev_;
tw_timer* tmp2 = tmp->next_;
delete tmp;
tmp = tmp2;
}
}
}
//更新时间轮的当前槽,向前走一步,以反映时间轮的转动
cur_slot_ = ++cur_slot_ % DEFAULT_SLOTS_NUM; //similar to cycle queue
}
#endif
下面是测试代码,类似上篇博客中升序链表的测试代码,仅有部分不同:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <pthread.h>
#include "time_wheel_timer.h"
#define FD_LIMIT 65535
#define MAX_EVENT_NUMBER 1024
#define TIME_SLOT 5
static int pipefd[2];
static time_wheel timer_lst;
static int epollfd = 0;
int setnonblocking( int fd )
{
int old_option = fcntl( fd, F_GETFL );
int new_option = old_option | O_NONBLOCK;
fcntl( fd, F_SETFL, new_option );
return old_option;
}
void addfd(int fd )
{
epoll_event event;
event.data.fd = fd;
event.events = EPOLLIN | EPOLLET;
epoll_ctl( epollfd, EPOLL_CTL_ADD, fd, &event );
setnonblocking( fd );
}
void sig_handler( int sig )
{
int save_errno = errno;
int msg = sig;
send( pipefd[1], ( char* )&msg, 1, 0 );
errno = save_errno;
}
void addsig( int sig )
{
struct sigaction sa;
memset( &sa, '\0', sizeof( sa ) );
sa.sa_handler = sig_handler;
sa.sa_flags |= SA_RESTART;
sigfillset( &sa.sa_mask );
assert( sigaction( sig, &sa, NULL ) != -1 );
}
void timer_handler()
{
timer_lst.tick();
alarm( TIME_SLOT );
}
void cb_func( client_data* user_data )
{
epoll_ctl( epollfd, EPOLL_CTL_DEL, user_data->sockfd_, 0 );
assert( user_data );
close( user_data->sockfd_ );
printf( "close fd %d\n", user_data->sockfd_ );
}
int main( int argc, char* argv[] )
{
if( argc <= 2 )
{
printf( "usage: %s ip_address port_number\n", basename( argv[0] ) );
return 1;
}
const char* ip = argv[1];
int port = atoi( argv[2] );
int ret = 0;
struct sockaddr_in address;
bzero( &address, sizeof( address ) );
address.sin_family = AF_INET;
inet_pton( AF_INET, ip, &address.sin_addr );
address.sin_port = htons( port );
int listenfd = socket( PF_INET, SOCK_STREAM, 0 );
assert( listenfd >= 0 );
int on = 1;
ret = setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
assert(ret != -1);
ret = bind( listenfd, ( struct sockaddr* )&address, sizeof( address ) );
assert( ret != -1 );
ret = listen( listenfd, 5 );
assert( ret != -1 );
epoll_event events[ MAX_EVENT_NUMBER ];
epollfd = epoll_create( 5 );
assert( epollfd != -1 );
addfd(listenfd );
ret = socketpair( PF_UNIX, SOCK_STREAM, 0, pipefd );
assert( ret != -1 );
setnonblocking( pipefd[1] );
addfd(pipefd[0] );
// add all the interesting signals here
addsig( SIGALRM );
addsig( SIGTERM );
bool stop_server = false;
client_data* users = new client_data[FD_LIMIT];
bool timeout = false;
alarm( TIME_SLOT );
while( !stop_server )
{
int number = epoll_wait( epollfd, events, MAX_EVENT_NUMBER, -1 );
if ( ( number < 0 ) && ( errno != EINTR ) )
{
printf( "epoll failure\n" );
break;
}
for ( int i = 0; i < number; i++ )
{
int sockfd = events[i].data.fd;
if( sockfd == listenfd )
{
struct sockaddr_in client_address;
socklen_t client_addrlength = sizeof( client_address );
int connfd = accept( listenfd, ( struct sockaddr* )&client_address, &client_addrlength );
addfd(connfd);
users[connfd].addr_ = client_address;
users[connfd].sockfd_ = connfd;
tw_timer* timer = timer_lst.add_timer(3 * TIME_SLOT);
timer->user_data_ = &users[connfd];
timer->timeout_callback_ = cb_func;
users[connfd].timer_ = timer;
}
else if( ( sockfd == pipefd[0] ) && ( events[i].events & EPOLLIN ) )
{
int sig;
char signals[1024];
ret = recv( pipefd[0], signals, sizeof( signals ), 0 );
if( ret == -1 )
{
// handle the error
continue;
}
else if( ret == 0 )
{
continue;
}
else
{
for( int i = 0; i < ret; ++i )
{
switch( signals[i] )
{
case SIGALRM:
{
timeout = true;
break;
}
case SIGTERM:
{
stop_server = true;
}
}
}
}
}
else if( events[i].events & EPOLLIN )
{
memset( users[sockfd].buf_, '\0', BUFFER_SIZE );
ret = recv( sockfd, users[sockfd].buf_, BUFFER_SIZE-1, 0 );
printf( "get %d bytes of client data %s from %d\n", ret, users[sockfd].buf_, sockfd );
tw_timer* timer = users[sockfd].timer_;
if( ret < 0 )
{
if( errno != EAGAIN )
{
cb_func( &users[sockfd] );
if( timer )
{
timer_lst.del_timer( timer );
}
}
}
else if( ret == 0 )
{
cb_func( &users[sockfd] );
if( timer )
{
timer_lst.del_timer( timer );
}
}
else
{
//send( sockfd, users[sockfd].buf, BUFFER_SIZE-1, 0 );
if( timer )
{
//下面这些注释代码是和上篇博客升序链表不同的地方之一
// time_t cur = time( NULL );
//timer->expire = cur + 3 * TIMESLOT;
// printf( "adjust timer once\n" );
//timer_lst.adjust_timer( timer );
tw_timer* new_timer = timer_lst.adjust_timer(timer, 3*TIME_SLOT);
new_timer->user_data_ = &users[sockfd];
new_timer->timeout_callback_ = cb_func;
users[sockfd].timer_ = new_timer;
}
}
}
else
{
// others
}
}
if( timeout )
{
timer_handler();
timeout = false;
}
}
close( listenfd );
close( pipefd[1] );
close( pipefd[0] );
close( epollfd );
delete [] users;
return 0;
}
对于时间轮而言,添加一个定时器的时间复杂度是O(1),删除一个定时器的时间复杂度也是O(1)(因为是双向链表直接利用prev指针),执行一个定时器的时间复杂度是O(n)(遍历某个槽的链表所有节点,因为有的节点轮数不是当前轮,所以我们不能凭借类似升序链表那样只遍历部分链表就知道后面的节点时间未到)。但实际上执行一个定时器任务的效率比O(n)好的多,因为时间轮将所有定时器散列到不同的链表上。时间轮的槽越多,每条链表上定时器数量越少。当采用多个轮子实现时间轮,执行一个定时器的时间复杂度接近O(1)。