标题:
C++中利用多线程实现定时器
[打印本页]
作者:
look_w
时间:
2017-11-18 14:22
标题:
C++中利用多线程实现定时器
#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();
}
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/)
Powered by Discuz! 7.0.0