服务器开发之定时器设计

很久之前听著名页游服务器主程讲座时,讲到过定时器的实现,基本思路如下(易语言)

       while(true)

       {

             对定时器进行排序。

             for(遍历定时器)

             {

                   if 如果定时器到:

                          callback;

                   else

                           break;

             }

             usleep(20);

         }

        按照这个思路,我们继续我们的设计:

1: 首先 定义一个Thread类:

        

复制代码
/*
 * Thread.h
 *
 *  Created on: Sep 11, 2012
 *      Author: root
 
*/

#ifndef THREAD_H_
#define THREAD_H_

#include <pthread.h>

class Thread {

public:
     enum THREADSTATE
    {
        IDLE,
        WORK,
        BUSY,
    };

public:

    Thread();

     virtual ~Thread();

     virtual  void* run( void) =  0;

     virtual  int start( void);

     virtual  int cancel( void);

    pthread_t get_pid()  const
    {
         return pid;
    }

protected:

    THREADSTATE _thread_state;

private:

    pthread_t pid;

     static  void* thread_entry( void* para);
};

#endif /* THREAD_H_ */
复制代码

        实现代码Thread.cpp:

View Code
复制代码
/*
 * Thread.cpp
 *
 *  Created on: Sep 11, 2012
 *      Author: root
 
*/

#include  " Thread.h "

Thread::Thread() {
     //  TODO Auto-generated constructor stub

}

Thread::~Thread() {
     //  TODO Auto-generated destructor stub
}

void* Thread::thread_entry( void* para)
{
    Thread *pThread = static_cast<Thread *>(para);
     return pThread->run();
}

int Thread::start( void)
{
     if(pthread_create(&pid, 0,thread_entry,static_cast< void *>( this)) <  0)
    {
        pthread_detach( this->pid);
         return - 1;
    }
     return  0;
}

int Thread::cancel( void)
{
    pthread_cancel( this->pid);
     return  0;
}
复制代码

 2:定义定时器,和定时器线程:

         TimerThread.h

        

复制代码
/*
 * Timer.h
 *
 *  Created on: Sep 11, 2012
 *      Author: root
 
*/

#ifndef TIMER_H_
#define TIMER_H_

#include  " Thread.h "
#include <list>

using  namespace std;

struct Timer
{

     void *_args;
     int (*_callback)();
     int _interval;
     int leftsecs;
     void open( int interval, int (*callback)())
    {
        _interval = interval *  1000;
        leftsecs = _interval;
        _callback = callback;
    }

     bool  operator < (Timer _timer)
    {
         return _timer.leftsecs <  this->leftsecs;
    }

     bool  operator == (Timer _timer)
    {
         return _timer.leftsecs ==  this->leftsecs;
    }

};

class TimerThread :  public Thread
{

public:

     static TimerThread* _instance;

     static TimerThread* get_instance();

     virtual  void* run( void);

     virtual ~TimerThread();

     void Register(Timer _timer);

     void unRegister(Timer _timer);

private:

    TimerThread();

    list<Timer> _timer_list;

};

extern unsigned  int get_systime_clock();



#define TIMERMANAGE TimerThread::get_instance()

#endif /* TIMER_H_ */
复制代码

 

          实现代码:TimerThread.cpp

View Code
复制代码
/*
 * Timer.cpp
 *
 *  Created on: Sep 11, 2012
 *      Author: root
 
*/

#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include  " Timer.h "


TimerThread* TimerThread::_instance;



TimerThread::TimerThread()
{

}

TimerThread::~TimerThread()
{

}

void* TimerThread::run( void)
{
     while( true)
    {
        unsigned  int start_clock = get_systime_clock();
         this->_timer_list.sort();
        list<Timer>::iterator iter;
         for(iter =  this->_timer_list.begin();
                iter !=  this->_timer_list.end();
                    iter ++)
        {
            iter->leftsecs --;
             if(iter->leftsecs ==  0)
            {
                iter->_callback();
                iter->leftsecs = iter->_interval;
            }
        }
        unsigned  int end_clock = get_systime_clock();

        usleep( 1000 + start_clock - end_clock);
    }
     return ( void*) 0;
}

void TimerThread::Register(Timer _timer)
{
     this->_timer_list.push_back(_timer);
}

void TimerThread::unRegister(Timer _timer)
{
     this->_timer_list.remove(_timer);
}

TimerThread* TimerThread::get_instance()
{
     if(_instance == NULL)
    {
        _instance =  new TimerThread();
    }
     return _instance;
}



unsigned  int get_systime_clock()
{
     struct timeval now;
    gettimeofday(&now,NULL);
     return now.tv_sec* 1000 + now.tv_usec/ 1000;
}
复制代码

         

 3: 测试函数:

View Code
复制代码
// ============================================================================
//  Name        : test.cpp
//  Author      : archy
//  Version     :
//  Copyright   : Your copyright notice
//  Description : Hello World in C++, Ansi-style
// ============================================================================

#include <iostream>
#include < string>
#include <stdio.h>
#include <sys/types.h>

#include  " Timer.h "


using  namespace std;

int handle_timeout()
{
    unsigned  int time = get_systime_clock();
    printf( " time out,%u\n ",time);
     return  0;
}

int main()
{
    Timer _timer;
    _timer.open( 1,handle_timeout);
    TIMERMANAGE->Register(_timer);
    TIMERMANAGE->start();
    getchar();
     return  0;
}
复制代码

       

目前存在的问题:定时不准,主要是由于usleep()之后 ,不能及时醒,这个是因为Linux线程调度引起的。

改进的方向:1. TimerThread 里面的list换成优先队列

                 2. 添加时间纠正,在测试中发现,每次大概慢100us左右,这对于长时间的定时器是致命。

也想听听广大网友的意见,感激不尽。

================================================================

#3楼 2012-09-11 19:54 | 杨文海  
你的代码有几个地方不是很优化:
1、每次都要遍历所有的定时器,其实没必要,只需要和最小的定时器比较即可,如果最小的都没超时,剩下的定时器完全没必要比较
2、TimerThread::get_instance 这个不是线程安全的,你可以看下单例模式线程安全如何做。

关于第一点,可行的办法是将所有的定时器弄成一个小根堆,每次只需要跟堆顶元素比较即可,添加、删除定时器其实就是一个调整小跟堆的过程,具体复杂度可参考堆排序。
  
#4楼 [ 楼主] 2012-09-12 08:13 | archy_yu  
@yahle
恩,很好的建议,谢谢,下个版本修正
  
#5楼 [ 楼主] 2012-09-12 08:14 | archy_yu  
@杨文海
确实没有考虑到多线程的问题,下个版本会添加线程保护
  
#6楼 [ 楼主] 2012-09-12 08:14 | archy_yu  
@coomisi
  
#7楼 [ 楼主] 2012-09-12 11:41 | archy_yu  
@yahle
有一个问题,定时器到达什么样的性能,才能放心的引入到程序中?
  
#8楼 [ 楼主] 2012-09-12 16:11 | archy_yu  
@杨文海
有一个问题,定时器到达什么样的性能,才能放心的引入到程序中?
  
#9楼 2012-10-16 14:47 | irons  
@archy_yu
@archy_yu
引用 @杨文海
确实没有考虑到多线程的问题,下个版本会添加线程保护

这个没必要。定时器系统设计为独立模块(单线程)比较好。用户在此基础上可以添加多线程设计。
  
#10楼 2012-10-16 14:47 | irons  
@archy_yu
引用 @杨文海
有一个问题,定时器到达什么样的性能,才能放心的引入到程序中?

排序效率测试。添加删除。
  
#11楼 2012-12-17 18:01 | yachi  
PriorityQueue。
参考java实现的这个。
  
#12楼 [ 楼主] 2579778 2012/12/17 18:23:52 2012-12-17 18:23 | archy_yu  
@yachi
好,多谢,多多交流指教啊
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值