Waitforsingleobject

Synchronization is a very hot topic in all threading subjects. Almost all the programs using threading are in some way will be implementing a synchronization object in their source.

Windows provides a number of synchronization objects and objects that are wait able on the synchronization objects. WaitForSingleObject is one such wait able object. This article explains how to use the WaitForSingleObject in a windows c++ program.

This WaitForSingleObject is a single object wait function. It requires a handle to be supplied as a parameter for it to wait on. The handle can be from objects like a thread, event, mutex, semaphore etc., The function WaitForSingleObject waits till the objects are in non-signaled state. Once these objects are signaled, then WaitForSingleObject function returns immediately.

The WaitForSingleObject function can also be made to wait for either a specified amount of milli -seconds or INFINITE amount of time. When this is set to a specified amount of time, the function WaitForSingleObject returns either when it is signaled or when the time specified has elapsed. If it is made to wait for INFINITE amount of time, then it waits till the object becomes signaled.

The biggest advantage or use of WaitForSingleObject is when there are a lot of threads used and there is a need to track if all of them are complete. For example there might be a program while closing, might need to exit all the threads, close all pipes, sockets etc., legally without aborting them. In such cases, we can put a wait using WaitForSingleObject and exit once all of them give a green signal and then close the program.

A small sample is provided using a thread, an event object on which the WaitForSingleObject function waits and exits after it becomes signaled.


// WaitForSingleObject Sample.cpp

#include <windows.h>
#include <iostream.h>

HANDLE hEvent;

DWORD WINAPI SampleThread(LPVOID iValue)
{
	int iFinish = 120;
	for(int i=100;i<=iFinish;i++)
		cout<<i<<endl;

	SetEvent(hEvent);
	return 0;
}

void main()
{
	HANDLE hThread;
	DWORD dwGenericThread;
	hThread = CreateThread(NULL,0,SampleThread,NULL,0,&dwGenericThread);
	if(hThread == NULL)
	{
	DWORD dwError = GetLastError();
	cout<<"SCM:Error in Creating thread"<<dwError<<endl ;
	return;
	}

	hEvent = CreateEvent(NULL,FALSE,FALSE,"Test");

	cout<<"Started waiting for the thread to complete.."<<endl ;
	WaitForSingleObject(hEvent,INFINITE);
	cout<<"Thread Completed."<<endl ;

	CloseHandle(hEvent);
}

As above the function WaitForSingleObject can be made to wait on all synchronization objects. There is another function WaitForMultipleObjects which can be used to wait on a multiple handles/objects.    WaitForSingleobject can also be used in small timer implementations because of its ability to wait for a specified amount of time.