C++中利用多线程实现定时器

     #ifndef CTIMER_H_
    #define CTIMER_H_
    #include 
    class CTimer
    {
    public:
     CTimer();
     ~CTimer();
     void StartTimer(unsigned int nElapse);
     void EndTimer();
     static DWORD WINAPI ThreadFunc (LPVOID pParam);
    private:
     unsigned int m_Elapse;
     HANDLE m_hThread;
    };
    #endif
     
    /********CTimer.cpp***********/
    #include 
    #include 
    #include "CTimer.h"
    using namespace std;
    CTimer::CTimer():m_Elapse(0), m_hThread(NULL)
    {
    }
    CTimer::~CTimer()
    {
    }
    void CTimer::StartTimer(unsigned int nElapse)
    {
     m_Elapse = nElapse;
     m_hThread = CreateThread(NULL, 0, ThreadFunc, (LPVOID)(&m_Elapse), 0, NULL);
    }
    void CTimer::EndTimer()
    {
     CloseHandle(m_hThread);
    }
    DWORD WINAPI CTimer::ThreadFunc(LPVOID pParam)
    {
     time_t t1, t2;
     double  Diff = 0;
     int elapse = *((int *)pParam);
     /*获取系统当前时间*/
     t1 = time(NULL);
     while(1)
     {
      /*以秒为单位获取系统当前时间*/
      t2 = time(NULL);
      /*比较第二次获取的时间与第一次的时间是不是间隔了两秒*/
      Diff = difftime(t2,t1);
      /*间隔两秒打印Diff和i*/
      if((int)Diff == elapse)
      {
       cout<<"Time out!"<

你可能感兴趣的:(Windows,Timer)