//start main function
HANDLE hSemaphore, hThread;
//create semaphore
hSemaphore = CreateSemaphore (NULL, // default security
attributes
2, // initial count
2, //maximum count
NULL); // object name
if (hSemaphore == NULL)
{
printf ("Error creating the semaphore\n");
exit (1);
}
//create child threads
for (i=0; i<3; i++)
{
hThread=CreateThread(NULL,0,foo,(LPVOID)i,0,&dwThreadID);
if (hThread)
printf ("Thread launched successfully\n");
else
//print error message and exit (-1)
}
//wait until child threads have exited
DWORD dwCThd = WaitForMultipleObjects (3, //count of
objects
hThread, //thread handle
TRUE, //wait for all
INFINITE); //time out interval
If (dwCThd != WAIT_OBJECT_0)
//Print error message and exit (-1)
//close handle for semaphore
CloseHandle (hSemaphore);
//close child thread handles
for (i=0; i<3; i++)
CloseHandle (hThread[i]);
//end of main function
/******
* function foo
******/
DWORD WINAPI foo (LPVOID num)
{
for( j = 0; j<3; j++)
{
//wait for single object
DWORD dwRes = WaitForSingleObject (hSemaphore,
INFINITE);
If (dwRes == WAIT_OBJECT_0)
//acquired the semaphore
else
//print error
// do something
// release semaphore
Long lpPreviousCount;
ReleaseSemaphore (hSemaphore,
1, // count of the semaphore object
// is to be increased &lpPreviousCount); //pointer to a 32-bit
variable
// for the previous count of
// the semaphore
Sleep (1000);
}
return 0;
}
|