思路描述:
- 1 使用QueryPerformanceXXX函数实现定时等待线程;
- 2 等待线程中周期向外发送系统事件;
- 3 类提供阻塞函数block(),方便用户放在周期处理的代码块开头。
源码:
#include "stdafx.h"
#include<Windows.h>
#include<map>
#include <string>
#include <fstream>
using namespace std;
#include <process.h>
//参数一表示 需要等待的时间 微秒为单位
int UsSleep(int us)
{
//储存计数的联合
LARGE_INTEGER fre;
//获取硬件支持的高精度计数器的频率
if (QueryPerformanceFrequency(&fre))
{
LARGE_INTEGER run,priv,curr;
run.QuadPart = fre.QuadPart * us / 1000000;//转换为微妙级
//获取高精度计数器数值
QueryPerformanceCounter(&priv);
do
{
QueryPerformanceCounter(&curr);
} while (curr.QuadPart - priv.QuadPart < run.QuadPart);
curr.QuadPart -= priv.QuadPart;
int nres = (curr.QuadPart * 1000000 / fre.QuadPart);//实际使用微秒时间
return nres;
}
return -1;//
}
class HTimer{
public:
HTimer(){};
~HTimer(){ m_bExitThread = true; };
void Init(int us){
_us = us;
//1安全属性,2:false自动复位,3:fasel初始态无信号,4:事件名
m_hEvt = CreateEvent(NULL,FALSE,FALSE,NULL);
m_bExitThread = false;
m_hThread = (HANDLE)_beginthread(waitThreadFunc, 0, this);
}
static void waitThreadFunc(LPVOID pObj){
HTimer *p = (HTimer*)pObj;
while(!p->m_bExitThread){
UsSleep(p->_us);
SetEvent(p->m_hEvt);
}
}
void Block(){
WaitForSingleObject(m_hEvt, INFINITE);
}
private:
int _us;
HANDLE m_hEvt;
HANDLE m_hThread;
bool m_bExitThread;
};
#include "time.h"
#include "sys/timeb.h"
UINT32 GetMSS(){
struct timeb timebuffer;
ftime(&timebuffer);
return (UINT32)((timebuffer.time%(86400)+28800)*1000 + timebuffer.millitm);
}
int _tmain(int argc, _TCHAR* argv[])
{
HTimer tt;
tt.Init(1000000);
while(1){ //实际使用中换成独立线程
tt.Block();
printf("\r\n time:%u",GetMSS());
}
return 0;
}
输出:精度控制在1毫秒。
time:63382448
time:63383448
time:63384449
time:63385449
time:63386449
time:63387449
time:63388449
time:63389449