多线程 Semaphore 回调函数 多媒体定时器的使用
//
//作用:WIN32API创建两个线程各自定时输出tickcount
//
//
// timerSemaphore.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "windows.h"
#include "mmsystem.h"
#pragma comment (lib,"winmm.lib")
#define ONE_MILLI_SECOND 1 //定义1ms和2s时钟间隔,以ms为单位 ;
#define TWO_SECOND 2000
#define TIMER_ACCURACY 1 //定义时钟分辨率,以ms为单位
HANDLE hEventOnTimer;
void CALLBACK TimerCallback(UINT wTimerID,UINT msg,DWORD dwUser,DWORD dw1,DWORD dw2)
{
::SetEvent(hEventOnTimer);
printf("timer callback! at tick: %d\n",::GetTickCount());
}
void ThreadProc()
{
while(1)
{
// ::ResetEvent(hEventOnTimer);
::WaitForSingleObject(hEventOnTimer,INFINITE); // 经过测试,没有与callback函数之间没有延时
printf("timer callback in Thread Proc! at tick: %d\n",::GetTickCount());
}
}
int main()
{
UINT TimerID_1ms;
TIMECAPS tc;
DWORD ThreadID;
hEventOnTimer=::CreateEvent(NULL,false,false,NULL); //关键!!!
//利用函数timeGetDeVCaps取出系统分辨率的取值范围,如果无错则继续;
if(timeGetDevCaps(&tc,sizeof(TIMECAPS))==TIMERR_NOERROR)
{ UINT wAccuracy=min(max(tc.wPeriodMin,TIMER_ACCURACY),tc.wPeriodMax);
//调用timeBeginPeriod函数设置定时器的分辨率
::timeBeginPeriod(wAccuracy);
}
// ::ResetEvent(hEventOnTimer);
if ((TimerID_1ms=timeSetEvent(30,1,(LPTIMECALLBACK)TimerCallback,0,TIME_PERIODIC))==0)
{
printf("cannot set timer!\n");
};
::CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadProc,&TimerID_1ms,0,&ThreadID);
getchar();
return 1;
}
posted on 2009-04-06 19:03 TobyLin的学习之路 阅读(526) 评论(0) 编辑 收藏 举报