Using the timer queue and events objects in thread synchronization
// For WinXp as a target, change appropriately
#define _WIN32_WINNT 0x0501
#include <windows.h>
#include <stdio.h>
HANDLE gDoneEvent;
VOID CALLBACK TimerRoutine(PVOID lpParam, BOOL TimerOrWaitFired)
{
if (lpParam == NULL)
{
printf("TimerRoutine()'s lpParam is NULL.\n");
}
else
{
// lpParam points to the argument; in this case it is an int...
printf("Timer routine called. Parameter is %d.\n", *(int*)lpParam);
}
SetEvent(gDoneEvent);
}
int main(void)
{
HANDLE hTimer = NULL;
HANDLE hTimerQueue = NULL;
int arg = 123;
// Use an event object to track the TimerRoutine() execution...
gDoneEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (!gDoneEvent)
{
printf("CreateEvent() failed, error: %d.\n", GetLastError());
return 1;
}
else
printf("CreateEvent() is OK.\n");
// Create the timer queue...
hTimerQueue = CreateTimerQueue();
if (!hTimerQueue)
{
printf("CreateTimerQueue() failed, error: %d.\n", GetLastError());
// May just return/exit with error code...
return 2;
}
else
printf("CreateTimerQueue() is OK.\n");
// Set a timer to call the timer routine in 10 seconds...
if (!CreateTimerQueueTimer(&hTimer, hTimerQueue, TimerRoutine, &arg, 10000, 0, 0))
{
printf("CreateTimerQueueTimer() failed, error: %d.\n", GetLastError());
// May just return/exit with error code...
return 3;
}
else
printf("CreateTimerQueueTimer() is OK and do the related task...\n");
// TODO: Do other useful work here...
printf("Call timer routine in 10 seconds...\n");
// Wait for the timer-queue thread to complete using an event object. The thread will signal the event at that time...
if (WaitForSingleObject(gDoneEvent, INFINITE) != WAIT_OBJECT_0)
printf("WaitForSingleObject() failed, error: %d.\n", GetLastError());
else
printf("WaitForSingleObject() is OK.\n");
// Delete all timers in the timer queue...
if (!DeleteTimerQueue(hTimerQueue))
printf("DeleteTimerQueue() failed, error: %d.\n", GetLastError());
else
printf("DeleteTimerQueue() is OK.\n");
return 0;
}
Output example:
CreateEvent() is OK.
CreateTimerQueue() is OK.
CreateTimerQueueTimer() is OK and do the related task...
Call timer routine in 10 seconds...
Timer routine called. Parameter is 123.
WaitForSingleObject() is OK.
DeleteTimerQueue() is OK.
Press any key to continue . . .
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Target platform: none, just for learning and fun
Header file: Standard and Windows
Additional library: Windows Platform SDK
Additional project setting: Set project to be compiled as C
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)
Other info: non-CLR or unmanaged
To do: Using the Windows timer queue and events objects for thread synchronization
To show: The Windows process and thread related functions used in Win32 C programming