天天看點

線程同步(計時器)

1.CreateWaitableTimer()函數建立等待計時器。

2.SetWaitableTimer()函數設定建立的計時器時間間隔。

3.CancelWaitableTimer()函數取消計時器。

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

#define WIN32_WINNT 0x500

#define ONE_SECOND 10000000

typedef struct _APC_PROC_ARG
{
    TCHAR *szText;
    DWORD dwValue;
}APC_PROC_ARG;

VOID CALLBACK TimerAPCProc(LPVOID lpArg,DWORD dwTimerLowValue,DWORD dwTimerHighValue)
{
    APC_PROC_ARG *pApcData=(APC_PROC_ARG *)lpArg;
    printf("Message :%s\n Value :%d\n\n",pApcData->szText,pApcData->dwValue);
    MessageBeep(MB_OK);
}

void main(void)
{
    HANDLE hTimer;
    BOOL bSuccess;
    INT64 qwDueTime;
    LARGE_INTEGER liDueTime;
    APC_PROC_ARG ApcData;
    ApcData.szText="message to apc proc.";
    ApcData.dwValue=1;

    hTimer=CreateWaitableTimer(NULL,FALSE,"MyTimer");
    if(!hTimer)
    {
        printf("CreateWaitableTimer failed with Error %d.",GetLastError());
        return;
    }
    else
    {
        _try
        {
            qwDueTime=-5*ONE_SECOND;
            liDueTime.LowPart=(DWORD)(qwDueTime & 0xFFFFFFFF);
            liDueTime.HighPart=(LONG)(qwDueTime >> 32);
            bSuccess=SetWaitableTimer(hTimer,&liDueTime,2000,TimerAPCProc,&ApcData,FALSE);
            if(bSuccess)
            {
                for(;ApcData.dwValue<10;ApcData.dwValue++)
                {
                    SleepEx(INFINITE,TRUE);
                }
            }
            else
            {
                printf("SetWaitableTimer failed with Error %d.",GetLastError());
            }
        }
        _finally
        {
            CloseHandle(hTimer);
        }
    }
}
           

繼續閱讀