网络编程定时器一:使用升序链表

之前一直对定时器这块不熟,今天来练练手。首先我们来看实现定时器的第一种方式,升序链表。

网络编程中应用层的定时器是很有必要的,这可以让服务端主动关闭时间很久的非活跃连接。另外一种解决方案是TCP的keepalive,但它只能检测真正的死连接,即客端主机断电,或者网线被拔掉这种情况。如果客端连接上,但什么都不做,keepalive是毫无办法的,它只能一定时间后不断的向客户端发送心跳包。

定时器通常至少要包含两个成员:一个超时时间(相对时间或绝对时间)和一个任务毁掉函数。有的时候还可能包含回调函数被执行时需要传入的参数,以及是否重启定时器等信息。如果使用双向链表,自然还需要指针成员。

我们将是用time函数作为定时器时间函数,它是相对时间,即从1970年某天到现在的描述,是一个数值,很容易用它和当前时间比较,后文分析。

下面实现了一个简单的升序定时器链表。升序定时器链表将其中定时器按照超时时间做升序排序。

#ifndef LIST_TIMER_H
#define LIST_TIMER_H

#include <time.h>
#include <memory>
#include <netinet/in.h>
#include <assert.h>

static const int BUFFER_SIZE = 64; 

class util_timer;   //前向声明

class client_data {
public:
    sockaddr_in                 addr_;    //客户端地址
    int                         sockfd_;  //客户端connfd
    char                        buf_[BUFFER_SIZE];  //每个客户端的缓冲区
    std::shared_ptr<util_timer> timer_;   //每个客户端的定时器
};

class util_timer {
public: //default constructor
    void (*timeout_callback_)(client_data* user_data);   //超时回调函数
public:
    time_t                       expire_;     //任务的超时时间,这里使用绝对时间
    client_data*                 user_data_;     //FIXME: how to replace it as a smart pointer.   //回调函数处理的客户数据,由电石气的执行者传给回调函数
    std::shared_ptr<util_timer>  prev_;   //指向前一个定时器
    std::shared_ptr<util_timer>  next_;   //指向下一个定时器
};

//定时器链表,它是一个升序、双向链表
class sort_timer_list { 
public: //default constructor and destructor
    void add_timer(const std::shared_ptr<util_timer>& timer);
    void adjust_timer(const std::shared_ptr<util_timer>& timer);
    void del_timer(const std::shared_ptr<util_timer>& timer);
    void tick();
private:
    void add_timer(const std::shared_ptr<util_timer>& timer,
                   const std::shared_ptr<util_timer>& lst_head);
private:
    std::shared_ptr<util_timer> head_;
    std::shared_ptr<util_timer> tail_;
};

//将目标定时器timer添加到链表中
void sort_timer_list::add_timer(const std::shared_ptr<util_timer>& timer)
{
    assert(timer != NULL);

    if(head_ == NULL){
        head_ = tail_ = timer;
        return;
    }
    //如果目标定时器的超时时间小于当前链表中所有定时器的超时时间,则把该定时器插入链表头部,作为链表的头节点。否则就需要调用重载函数add_timer把它插入到链表中合适的位置,以保证链表的升序特性
    if(timer->expire_ < head_->expire_){
        timer->next_ = head_;
        head_->prev_ = timer;
        head_ = timer;
    }
    else
        add_timer(timer, head_);  //invoke private add_timer
}

//一个重载
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值