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


         使用多线程技术实现了一个简单的定时器类:

                

            /********CTimer.h***********/

     #ifndef CTIMER_H_
    #define CTIMER_H_

    #include <Windows.h>

    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 <time.h>
    #include <iostream>
    #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!"<<endl;
       t1 = t2;
      }    
     }
     return 0;
    }

    /********测试程序************/

    #include "CTimer.h"

    void main()
    {
     CTimer timer;
     timer.StartTimer(1);


     Sleep(8000);
     timer.EndTimer();
    }

  • 相关阅读:
    请注意更新TensorFlow 2.0的旧代码
    tf.cast用法
    文件句柄
    Python学习(四)cPickle的用法
    机器都会学习了,你的神经网络还跑不动?来看看这些建议
    Hadoop集群管理之配置文件
    SQL之case when then用法
    关于2014
    Oracle之虚拟索引
    Linux之Ganglia源码安装
  • 原文地址:https://www.cnblogs.com/zhangyunlin/p/6167994.html
Copyright © 2020-2023  润新知