Linux下的定时器类实现(select定时+线程)

 

更好的计时器类实现LINUX RTC机制实现计时器类
      很多时候需要在LINUX下用到定时器,但像setitimer()和alarm()这样的定时器有时会和sleep()函数发生冲突,这样就给编程带来了很大的困难。
    写了一个定时器的类,使用select进行精确定时。而且可以在系统中创建不限数量的定时器,且互不干扰。类的内部采用线程实现。即线程+select。代码如下:

CTimer.h: /* * CTimer.h * * Created on: 2009-7-13 * Author: DEAN */ ////////////////////////////////////////////////////////////////////////// // This class provide a timer to finish some works. // Call SetTimer() to set the timer_interval. Call StartTimer() // to enable it and call StopTimer() to stop it. // The work you want to do should be written on OnTimer // function. ////////////////////////////////////////////////////////////////////////// #ifndef CTIMER_H_ #define CTIMER_H_ #include <pthread.h> #include <sys/time.h> class CTimer { private: pthread_t thread_timer; long m_second, m_microsecond; static void *OnTimer_stub(void *p) { (static_cast<CTimer*>(p))->thread_proc(); } void thread_proc(); void OnTimer(); public: CTimer(); CTimer(long second, long microsecond); virtual ~CTimer(); void SetTimer(long second,long microsecond); void StartTimer(); void StopTimer(); }; #endif /* CTIMER_H_ */ CTimer.cpp: /* * CTimer.cpp * * Created on: 2009-7-13 * Author: DEAN */ #include "CTimer.h" #include <iostream> #include <sys/select.h> #include <time.h> #include <pthread.h> using namespace std; //////////////////////////public methods////////////////////////// CTimer::CTimer(): m_second(0), m_microsecond(0) { } CTimer::CTimer(long second, long microsecond) : m_second(second), m_microsecond(microsecond) { } CTimer::~CTimer() { } void CTimer::SetTimer(long second, long microsecond) { m_second = second; m_microsecond = microsecond; } void CTimer::StartTimer() { pthread_create(&thread_timer, NULL, OnTimer_stub, this); } void CTimer::StopTimer() { pthread_cancel(thread_timer); pthread_join(thread_timer, NULL); //wait the thread stopped } //////////////////////////private methods////////////////////////// void CTimer::thread_proc() { while (true) { OnTimer(); pthread_testcancel(); struct timeval tempval; tempval.tv_sec = m_second; tempval.tv_usec = m_microsecond; select(0, NULL, NULL, NULL, &tempval); } } void CTimer::OnTimer() { cout<<"Timer once..."<<endl; } 示例代码main.cpp: /* * main.cpp * * Created on: 2009-7-19 * Author: DEAN */ #include <iostream> #include "CTimer.h" using namespace std; int main() { CTimer t1(1,0),t2(1,0); //构造函数,设两个定时器,以1秒为触发时间。参数1是秒,参数2是微秒。 t1.StartTimer(); t2.StartTimer(); sleep(10); return 0; } 

    使用的话其实很简单,只要写一下OnTimer()函数的内容就行了,定时器会在每个定时器触发时调用此函数。里面用到的一个点是使用类的成员函数作为线程体的执行函数,需要进行一下静态类型转换。在上面已标出:
    static void *OnTimer_stub(void *p)
    {
        (static_cast<CTimer*>(p))->thread_proc();
    }
   
有了这个类以后,使用定时器就方便多了:-)

 

你可能感兴趣的:(JOIN,thread,linux,timer,struct,null)