Windows Thread Synchronization 14






The WaitForSingleObject() Example


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


The WaitForSingleObject() Example: Creating new Win32 empty console application project


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


The WaitForSingleObject() Example: Adding new C++ source file


Next, add the following source code.


// Primary thread waits till child thread terminates

#include <windows.h>

#include <stdio.h>


// Thread counts till PassVal

void ThreadMain(LONG PassVal)


      LONG i;




            wprintf(L"ThreadMain() - count #%d\n", i);




// Main process & thread

int wmain(void)


      DWORD ThreadID, dwRet;

      HANDLE hTh;


      // Creates a thread to execute within the virtual address space of the calling process





            wprintf(L"CreateThread() failed, error %u\n", GetLastError());

            return 1;



            wprintf(L"CreateThread() is OK, thread ID %u\n", ThreadID);


      // Blocks/wait till thread terminates

      // Waits until the specified object is in the signaled state or

      // the time-out interval elapses.

      // The INFINITE parameter make the function return only when the object is signaled

      wprintf(L"Waiting the child thread terminates/signaled...\n");

      dwRet = WaitForSingleObject(hTh,INFINITE);

      wprintf(L"WaitForSingleObject() returns value is 0X%.8X\n", dwRet);




      case WAIT_ABANDONED:

            wprintf(L"Mutex object was not released by the thread that\n"

                  L"owned the mutex object before the owning thread terminates...\n");


      case WAIT_OBJECT_0:

            wprintf(L"The child thread state was signaled!\n");


      case WAIT_TIMEOUT:

            wprintf(L"Time-out interval elapsed, and the child thread's state is nonsignaled.\n");


      case WAIT_FAILED:

            wprintf(L"WaitForSingleObject() failed, error %u\n", GetLastError());




      if(CloseHandle(hTh) != 0)

            wprintf(L"hTh's child thread handle was closed successfully!\n");


            wprintf(L"Failed to close hTh child thread handle, error %u\n", GetLastError());


      wprintf(L"Main process & thread ready to exit...\n");


      return 0;



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


The WaitForSingleObject() Example: Sample console program output





< Thread Synchronization 13 | Thread Synchronization Programming | Win32 Programming | Thread Synchronization 15 >