Code:
#include <process.h>
#include <windows.h>
#include <stdio.h>
#include <time.h>
int randNum1 = 0;
int randNum2 = 0;
int greatCommonDivisor = 0;
HANDLE hThread1;
unsigned threadID1;
HANDLE hThread2;
unsigned threadID2;
HANDLE ghMutex;
int euclidGCD( int a, int b )
{
if (b == 0)
return a;
else
return euclidGCD( b, a % b );
}
unsigned __stdcall SecondThreadFunc( void* pArguments )
{
DWORD dwWaitResult2;
for(int indx = 0; indx < 10; indx++)
{
dwWaitResult2 = WaitForSingleObject(
ghMutex,
5000L);
switch (dwWaitResult2)
{
case WAIT_OBJECT_0:
__try
{
printf( "In second thread...\n" );
greatCommonDivisor = euclidGCD(randNum1, randNum2);
printf( "Greatest common divisor is %d\n", greatCommonDivisor );
}
__finally
{
// Release ownership of the mutex object.
if (! ReleaseMutex(ghMutex))
{
// Deal with error.
}
break;
}
case WAIT_TIMEOUT:
return FALSE;
case WAIT_ABANDONED:
return FALSE;
}
}
return 0;
}
void main()
{
// initialize random seed:
// srand ( time(NULL) ); // use after design and testing
srand ( 4 ); // used for design and testing
// Create a mutex with no initial owner
ghMutex = CreateMutex(
NULL, // default security attributes
FALSE, // initially not owned
NULL); // unnamed mutex
printf( "Creating second thread...\n" );
// Create the second thread.
hThread2 = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc, NULL, 0,
&threadID2 );
DWORD dwWaitResult;
for(int i = 0; i < 10; i++)
{
// Request ownership of mutex.
dwWaitResult = WaitForSingleObject(
ghMutex,
5000L);
switch (dwWaitResult)
{
// The thread got mutex ownership.
case WAIT_OBJECT_0:
__try
{
printf( "In first thread...\n" );
/* generate random numbers: */
randNum1 = rand() % 100 + 1;
randNum2 = rand() % 100 + 1;
printf( "Random number one is %d\n", randNum1 );
printf( "Random number two is %d\n", randNum2 );
}
__finally
{
// Release ownership of the mutex object.
if (! ReleaseMutex(ghMutex))
{
}
break;
}
case WAIT_TIMEOUT:
return;
case WAIT_ABANDONED:
return;
}
}
_endthreadex( 0 );
// Destroy the thread object.
// CloseHandle( hThread1 );
CloseHandle( hThread2 );
}