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;

 

    for(i=0;i<PassVal;i++)

      {

            wprintf(LThreadMain() - 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

    hTh=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadMain,(LPVOID)10,0,&ThreadID);

 

    if(hTh==NULL)

      {

            wprintf(LCreateThread() failed, error %u\n, GetLastError());

            return 1;

      }

      else

            wprintf(LCreateThread() 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(LWaiting the child thread terminates/signaled...\n);

      dwRet = WaitForSingleObject(hTh,INFINITE);

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

 

      switch(dwRet)

      {

      case WAIT_ABANDONED:

            wprintf(LMutex object was not released by the thread that\n

                  Lowned the mutex object before the owning thread terminates...\n);

            break;

      case WAIT_OBJECT_0:

            wprintf(LThe child thread state was signaled!\n);

            break;

      case WAIT_TIMEOUT:

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

            break;

      case WAIT_FAILED:

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

            ExitProcess(0);

      }

 

      if(CloseHandle(hTh) != 0)

            wprintf(LhTh's child thread handle was closed successfully!\n);

      else

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

 

      wprintf(LMain 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 >