Linux高性能server编程——定时器

摘要:
https://blog.csdn.net/walkerkalr/article/details/36869913计时器服务器程序通常管理许多计时事件。我们需要将每个计时事件封装到计时器中。Linux提供了三种计时方法:1。插座选项SO_ RECVTIMEO和SO_ SNDTIMEO通常,SIGALRM信号是根据固定频率生成的,即,由报警或设置器功能设计的定时周期T保持不变。清单2定义了一个计时器列表,清单3显示了如何使用SIGALRM信号来处理非活动连接。I/O复用系统调用Linux下的三组I/O复用系统呼叫具有超时参数,因此它们不仅可以处理信号和I/O事件。它还可以统一处理定时事件。
版权声明:本文为博主原创文章。未经博主允许不得转载。 https://blog.csdn.net/walkerkalr/article/details/36869913


定时器

服务器程序通常管理着众多定时事件。因此有效组织这些定时事件,使之能在预期的时间点被触发且不影响服务器的主要逻辑,对于服务器的性能有着至关重要的影响。位置我们要将每一个定时事件封装成定时器。并使用某种容器类型的数据结构,比方链表、排序链表和时间轮将全部定时器串联起来,以实现对定时事件的统一管理。

Linux提供三种定时方法:

1.socket选项SO_RECVTIMEOSO_SNDTIMEO

2.SIGALRM信号

3.I/O复用系统调用的超时參数

socket选项SO_RCVTIMEOSO_SNDTIMEO

SO_RCVTIMEOSO_SNDTIMEO选项分别用来设置socket接收数据超时时间和发送数据超时时间。因此这两个选项仅对数据接收和发送相关的socket专用系统调用有效。这些系统调用包含sendsendmsgrecvrecvmsgacceptconnect

程序清单1展示了使用SO_SNDTIMEP选项来定时:

SIGALRM信号

alarmsetitimer函数设置的实时闹钟一旦超时。将触发SIGALRM信号。

因此,我们能够利用该信号的信号处理函数来处理定时任务。

可是。假设要处理多个定时任务,我们就须要不断触发SIGALRM信号,并在其信号处理函数中运行到期的任务。一般而言,SIGALRM信号依照固定频率生成,即由alarmsetitimer函数设计的定时周期T保持不变。假设某个定时任务的超时时间不是T的整数倍,那么它实际被运行的时间和预期的时间将略有偏差。

因此定时周期T反映了定时的精度。

程序清单2定义了一个定时器链表,程序清单3展示怎样使用SIGALRM信号处理非活动连接。

I/O复用系统调用

Linux下的3I/O复用系统调用都带有超时參数,因此他们不仅能允许处理信号和I/O事件。也能统一处理定时事件。

可是因为I/O复用系统可能在超时时间到期之前就返回。所以假设我们能要利用它们来定时,就须要不断更新定时參数以反映剩余的时间:

程序清单4展示了利用I/O复用系统调用定时:

 

高性能定时器

时间轮

基于排序链表的定时器存在一个问题:加入定时器的效率偏低。

以下我们要讨论的时间轮攻克了这个问题,一种简单的时间轮如图所看到的:

Linux高性能server编程——定时器第1张

上图所看到的的时间轮,实现指针指向轮子的一个槽。

它以恒定的速度顺时转动。每转动一步就指向下一个槽。每次转动称为一个滴答。

一个滴答的时间称为时间轮的槽间隔si。它时间上就是心搏时间。该时间轮共同拥有N个槽。因此转一圈时间是N*si。每一个槽指向一跳定时器链表,每条链表上的定时器具有同样的特征:他们的定时时间差JN*si的整数倍。非常显然,对时间轮而言,要提高定时精度。就要使si值足够小;要提高运行效率。则要求N值足够大。

时间堆

前面讨论的定时方案都是以固定是频率调用心搏函数tick,并在当中一次检測到期的定时器,然后运行到期定时器上的回调函数。设计定时器的还有一种思路是:将全部定时器中超时时间最小的一个定时器的超时值作为心搏间隔。

这样,一旦心搏函数tick被调用,超时时间最小的定时器必定到期,我们就能够在tick函数中处理该定时器。

然后,再次从剩余的定时器中找出超时时间最小的一个,并将这段最小时间设置为下一次心搏间隔。时间堆就是利用最小堆来是实现上述方案。


程序清单1:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int timeout_connect( const char* ip, int port, int time )
{
    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 sockfd = socket( PF_INET, SOCK_STREAM, 0 );
    assert( sockfd >= 0 );

    struct timeval timeout;
    timeout.tv_sec = time;
    timeout.tv_usec = 0;
    socklen_t len = sizeof( timeout );
    ret = setsockopt( sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeout, len );
    assert( ret != -1 );

    ret = connect( sockfd, ( struct sockaddr* )&address, sizeof( address ) );
    if ( ret == -1 )
    {
        if( errno == EINPROGRESS )
        {
            printf( "connecting timeout
" );
            return -1;
        }
        printf( "error occur when connecting to server
" );
        return -1;
    }

    return sockfd;
}

int main( int argc, char* argv[] )
{
    if( argc <= 2 )
    {
        printf( "usage: %s ip_address port_number
", basename( argv[0] ) );
        return 1;
    }
    const char* ip = argv[1];
    int port = atoi( argv[2] );

    int sockfd = timeout_connect( ip, port, 10 );
    if ( sockfd < 0 )
    {
        return 1;
    }
    return 0;
}
程序清单2:
#ifndef LST_TIMER
#define LST_TIMER

#include <time.h>

#define BUFFER_SIZE 64
class util_timer;
struct client_data
{
    sockaddr_in address;
    int sockfd;
    char buf[ BUFFER_SIZE ];
    util_timer* timer;
};

class util_timer
{
public:
    util_timer() : prev( NULL ), next( NULL ){}

public:
   time_t expire; 
   void (*cb_func)( client_data* );
   client_data* user_data;
   util_timer* prev;
   util_timer* next;
};

class sort_timer_lst
{
public:
    sort_timer_lst() : head( NULL ), tail( NULL ) {}
    ~sort_timer_lst()
    {
        util_timer* tmp = head;
        while( tmp )
        {
            head = tmp->next;
            delete tmp;
            tmp = head;
        }
    }
    void add_timer( util_timer* timer )
    {
        if( !timer )
        {
            return;
        }
        if( !head )
        {
            head = tail = timer;
            return; 
        }
        if( timer->expire < head->expire )
        {
            timer->next = head;
            head->prev = timer;
            head = timer;
            return;
        }
        add_timer( timer, head );
    }
    void adjust_timer( util_timer* timer )
    {
        if( !timer )
        {
            return;
        }
        util_timer* tmp = timer->next;
        if( !tmp || ( timer->expire < tmp->expire ) )
        {
            return;
        }
        if( timer == head )
        {
            head = head->next;
            head->prev = NULL;
            timer->next = NULL;
            add_timer( timer, head );
        }
        else
        {
            timer->prev->next = timer->next;
            timer->next->prev = timer->prev;
            add_timer( timer, timer->next );
        }
    }
    void del_timer( util_timer* timer )
    {
        if( !timer )
        {
            return;
        }
        if( ( timer == head ) && ( timer == tail ) )
        {
            delete timer;
            head = NULL;
            tail = NULL;
            return;
        }
        if( timer == head )
        {
            head = head->next;
            head->prev = NULL;
            delete timer;
            return;
        }
        if( timer == tail )
        {
            tail = tail->prev;
            tail->next = NULL;
            delete timer;
            return;
        }
        timer->prev->next = timer->next;
        timer->next->prev = timer->prev;
        delete timer;
    }
    void tick()
    {
        if( !head )
        {
            return;
        }
        printf( "timer tick
" );
        time_t cur = time( NULL );
        util_timer* tmp = head;
        while( tmp )
        {
            if( cur < tmp->expire )
            {
                break;
            }
            tmp->cb_func( tmp->user_data );
            head = tmp->next;
            if( head )
            {
                head->prev = NULL;
            }
            delete tmp;
            tmp = head;
        }
    }

private:
    void add_timer( util_timer* timer, util_timer* lst_head )
    {
        util_timer* prev = lst_head;
        util_timer* tmp = prev->next;
        while( tmp )
        {
            if( timer->expire < tmp->expire )
            {
                prev->next = timer;
                timer->next = tmp;
                tmp->prev = timer;
                timer->prev = prev;
                break;
            }
            prev = tmp;
            tmp = tmp->next;
        }
        if( !tmp )
        {
            prev->next = timer;
            timer->prev = prev;
            timer->next = NULL;
            tail = timer;
        }
        
    }

private:
    util_timer* head;
    util_timer* tail;
};

#endif
程序清单3
#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 "lst_timer.h"

#define FD_LIMIT 65535
#define MAX_EVENT_NUMBER 1024
#define TIMESLOT 5

static int pipefd[2];
static sort_timer_lst 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 epollfd, 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, '

免责声明:内容来源于网络,仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇路由协议基础Blend4精选案例图解教程(四):请给我路径指引下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

boost asio 学习(七) 网络基础 连接器和接收器(TCP示例)

http://www.gamedev.net/blog/950/entry-2249317-a-guide-to-getting- started-with-boostasio?pg=8 7. Networking basics: connectors and acceptors (TCP)我们来学习boost的TCP网络编程。之前的篇章已经介绍了网络系统...

android 定时器的使用

1、android中通常是使用AlarmManager来定时启动一个单次或重复多次操作的。具体的说就是我们通过AlarmManager设定一个时间和注册一个intent到系统中,然后在该时间到来时,系统为我们发送一个广播,即执行我们设定的Intent(要执行的操作),通常我们使用 PendingIntent来实现“要执行的操作”,PendingIntent...

安装Linux应用软件的五种基本方法

要充分发挥电脑的作用,就得有大量的应用软件,完成不同的工作。在Windows环境中安装各种应用软件的思路与方法,想必大家早已熟悉。然而,在使用Linux时,我们却总会被这些本不应该是问题的问题所困扰:怎么安装应用软件?我的软件安装在什么地方?如何删除不要的应用软件?……   下面,我们就一起来认识一下这些方面的知识。 一、解析Linux应用软件安装包...

linux编程lib的使用

今天由于要用到静态链接库,所以就学习了一下相关知识,总结如下:静态链接库(一般命名为libxxx.a)就是很多.o文件的集合,在你的项目中如果有一个子模快,这个子模块只是给总控模块提供一个函数接口,那么你就可以考虑把这个子模快编译成静态链接库libxxx.a,然后在总控模块中编译的时候,只需-L包含链接库所在的目录,再-lxxx引用链接库就行.当然,你也可...

Linux根文件系统分析之init和busybox

Hi,大家好!我是CrazyCatJack。今天给大家讲解Linux根文件系统的init进程和busybox的配置及编译。 先简单介绍一下,作为一个嵌入式系统,要想在硬件上正常使用的话。它的软件组成大概有这三部分:1)bootloader 2)嵌入式系统kernel 3)根文件系统 。这其实非常好理解,类比于PC上的操作系统,首先我们需要类似BIOS的东东...

LINUX环境下,达梦数据库8配置ODBC连接

1、检查gcc包 [root@localhost ~]#rpm -qa|grep gcc 如若没有安装,则使用如下方式安装。 安装gcc包 [root@localhost ~]#yum install -y gcc 2、cd到unixODBC安装包的目录 3、解压安装包,执行指令 [root@localhost home]#tar -xzvf unixO...