I was working on this program a year ago and wanted to check something on it but I have some errors on it and was wanting to know if someone very knowledgeable and take a look at this and offer me and advice to make it run. I get some undefined issues and think I may have accidentally made a change when I shouldnt have...
#include <windows.h>
#include <stdio.h>
#include <process.h>
#include <ctime>
#include <iostream>
#include <cstdlib>
using namespace std;
//DECLARE GLOBAL VARIABLES
int num1 = 0;
int num2 = 0;
int abc_output = 0;
//FUNCTION TO TEST IF NUM2 EQUALS ZERO AND TO RETURN NUM1 AND ANC IF IT DOES
int abc(int num1, int num2)
{
if (num2 == 0)
return num1;
return abc(num2, num1 % num2);
}
//BEGIN RANDOM NUMBER TEST FUNCTION
void randomNumber()
{
num1 = 0;
num2 = 0;
srand((unsigned int)time(NULL));
int num1 = rand()% 100;
int num2 = rand()% 100;
cout << "The first random number is " << num1 << "." << endl;
cout << "The second random number is " << num2 << "." << endl;
}
//CREATE AN UNSIGNED COUNTER AND HANDLE
unsigned counter;
HANDLE hMutex;
unsigned __stdcall SecondThreadFunc(void* pArguments)
{
cout << "In second thread..." << endl;
DWORD checkWaitResult;
while (counter < 10)
{
//REQUEST OWNERSHIP WILL NEED TO BE PERFORMED
checkWaitResult = WaitForObject(hMutex, 5000L);
switch (dwWaitResult)
{
// The thread got mutex ownership.
case WAIT_OBJECT_0:
__try
{
if (counter % 2)
{
counter++;
cout << " Thread #1" ;
randomNumber();
cout << "Thread Two Counter is-> %d" << endl << counter;
}
}
__finally
{
// Release ownership of the mutex object.
if (! ReleaseMutex(hMutex))
{
//ERROR WILL BE EXPECTED
}
break;
}
// Cannot get mutex ownership due to time-out.
case WAIT_TIMEOUT:
{
// Got ownership of the abandoned mutex object.
return false;
}
case WAIT_ABANDONED:
{
return false;
}
}
}
_endthreadex( 0 );
return 0;
}
int main()
{
HANDLE hThread;
unsigned threadID;
counter = 0;
hMutex = CreateMutex(NULL, FALSE, (LPCWSTR) "MutexToProtectDatabase");
if (hMutex == NULL)
{
// Check for error.
}
cout << "Creating second thread..." << endl;
// Create the second thread.
hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc, NULL, 0, &threadID );
DWORD dwWaitResult;
while (counter < 10)
{
// Request ownership of mutex.
dwWaitResult = WaitForSingleObject(hMutex, 5000L);
switch (dwWaitResult)
{
// The thread got mutex ownership.
case WAIT_OBJECT_0:
__try
{
if (!(counter % 2))
{
cout << " Thread #2" ;
counter++;
abc(num1,num2) = abc_output;
cout << "Primary Thread Counter is-> %d" << endl << counter;
}
}
__finally
{
// Release ownership of the mutex object.
if (! ReleaseMutex(hMutex))
{
// Deal with error.
}
break;
}
// Cannot get mutex ownership due to time-out.
case WAIT_TIMEOUT:
{
// Got ownership of the abandoned mutex object.
return false;
}
case WAIT_ABANDONED:
{
return false;
}
}
}
WaitForSingleObject( hThread, INFINITE );
cout << "Counter should be 10; it is-> %d" << endl << counter);
// Destroy the thread object.
CloseHandle( hThread );
return 0;
}