Using the timer and waitable timer objects in thread synchronization


// For WinXp as a target, change appropriately

#define _WIN32_WINNT 0x0501

#include <windows.h>

#include <stdio.h>


int main(void)






// Create a waitable timer.

hTimer = CreateWaitableTimer(NULL, TRUE, L"WaitableTimer");

if (!hTimer)


printf("CreateWaitableTimer() failed, error: %d.\n", GetLastError());

return 1;



printf("CreateWaitableTimer() is OK.\n");


// Next step...

printf("Waiting for 10 seconds...\n");


// Set a timer to wait for 10 seconds.

if (!SetWaitableTimer(hTimer, &liDueTime, 0, NULL, NULL, 0))


printf("SetWaitableTimer() failed, error: %d.\n", GetLastError());

return 2;



printf("SetWaitableTimer() is OK.\n");


// Wait for the timer.

if (WaitForSingleObject(hTimer, INFINITE) != WAIT_OBJECT_0)

printf("WaitForSingleObject() failed, error: %d.\n", GetLastError());


printf("Timer was signaled.\n");

return 0;



Output example:


CreateWaitableTimer() is OK.

Waiting for 10 seconds...

SetWaitableTimer() is OK.

Timer was signaled.

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 and waitable timer object for thread synchronization

To show: The Windows process and thread related functions used in Win32 C programming



C and C++ Programming Resources | C & C++ Code Example Index