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();
}