Windows Thread Synchronization 25

 

 

 

Using Waitable Timer Objects Program Example

 

The following example creates a timer that will be signaled after a 10 second delay. First, the code uses the CreateWaitableTimer() function to create a waitable timer object. Then it uses the SetWaitableTimer() function to set the timer. The code uses the WaitForSingleObject() function to determine when the timer has been signaled.

Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.

 

Using Waitable Timer Objects Program Example: Creating new Win32 empty console application project

 

 

Then, add the source file and give it a suitable name.

 

Using Waitable Timer Objects Program Example: Adding new C++ source file to the existing project

 

Next, add the following source code.

 

#include <windows.h>

#include <stdio.h>

 

int wmain()

{

    HANDLE hTimer = NULL;

    // Used to represent a 64-bit signed integer value

    // or very large number...

    LARGE_INTEGER liDueTime;

 

    liDueTime.QuadPart = -100000000LL;

 

    // Create an unnamed waitable timer.

    hTimer = CreateWaitableTimer(NULL, TRUE, NULL);

    if (NULL == hTimer)

    {

        wprintf(LCreateWaitableTimer() failed, error %d\n, GetLastError());

        return 1;

    }

      else

            wprintf(LCreateWaitableTimer() is OK, unnamed waitable timer was created\n);

 

    // Set a timer to wait for 10 seconds.

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

    {

        wprintf(LSetWaitableTimer() failed, error %d\n, GetLastError());

        return 2;

    }

      else

            wprintf(LSetWaitableTimer() is OK, waiting for 10 seconds...\n);

 

    // Wait for the timer.

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

        wprintf(LWaitForSingleObject() failed, error %d\n, GetLastError());

    else

            wprintf(LWaitForSingleObject() - timer was signaled...\n);

 

    return 0;

}

 

Build and run the project. The following screenshot is a sample output.

 

Using Waitable Timer Objects Program Example: A sample console program output

 

 

 

< Thread Synchronization 24 | Thread Synchronization Programming | Win32 Programming | Thread Synchronization 26 >