I need to know how i did? Any review will be appreciated...
/**program description:
*
* this simple program represents
* the basic concept of threads.
* main() process will create a
* thread that calculate numbers
* while main() output the results.
* main() and threadProcess() share
* share data from a same memory.
* threadProcess() add two numbers
* and dump the result into totalNumber.
* On the other hand, main() uses
* totalNumber to output the result.
* Thus, totalNumber is the shared scope.
* To avoid collision, i used mutex.
*
*/
#include <iostream>
#include <windows.h>
using namespace std;
int totalNumber = 0;
bool threadStarted = false;
HANDLE mutexHandle = NULL;
void threadProcess()
{
threadStarted = true;
for (int i=0; i < 10; i++)
{
WaitForSingleObject(mutexHandle, INFINITE);
cout<<"threadProcess() is calculating: "<<endl;
totalNumber += i;
//make thread procedure in same
//speed as main() process
Sleep(10);
ReleaseMutex(mutexHandle);
}
}
int main()
{
mutexHandle = CreateMutex(NULL, false, NULL);
HANDLE threadHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadProcess, NULL, 0, NULL);
//let thread starts first - main()
//somewhat starts faster than the
//spwaned process
while(!threadStarted) { }
for(int i = 0; i < 10; i++)
{
WaitForSingleObject(mutexHandle, INFINITE);
cout<<"main() is giving out solution: "<<endl;
cout<<totalNumber<<endl;
//make main() process run in same speed
//with the created thread
Sleep(10);
ReleaseMutex(mutexHandle);
}
//wait for the thread to finish
//in case its hanging around
WaitForSingleObject(threadHandle, INFINITE);
CloseHandle(mutexHandle);
cin.get();
return 0;
}