Hi,
I'm new in c++ thread programming, so I made a short program to understand how threads work in c++. However, the result is not what I expected, could anybody please take a look at this code and see if I did something wrong:
There is a glob_temp_var whose value is updated at each thread calling and it is printed out at two points: point 1 and point 2, points before and after updating in thread function. Although the glob_temp_var is changing inside the thread function, in point 2 the not-updated value of that, i.e. the value before going into the thread function, is printed out!
I think it is not correct, does anybody have any explanation or suggestion?
Thanks.
Code:
#include <iostream>
#include <windows.h>
#include <process.h>
#include <time.h>
HANDLE hEvent[MAX_CPU_COUNT];
HANDLE StartEvent[MAX_CPU_COUNT];
int glob_temp_var=0;
static void Thread1 (LPVOID lpParam){
while (true){
WaitForSingleObject(StartEvent[0], INFINITE);
glob_temp_var++;
ResetEvent(StartEvent[0]);
SetEvent(hEvent[0]);
}
}
int
main(int argc, char** argv)
{
for (int i=0; i<MAX_CPU_COUNT; i++){
hEvent[i] = CreateEvent( NULL, TRUE, TRUE, NULL );
StartEvent[i] = CreateEvent( NULL, TRUE, TRUE, NULL );
}
_beginthread( Thread1, 0, NULL );
Sleep(1000);
for (int t=0;t<duration;t++){
std::cout<<glob_temp_var; //////////////// point 1
for (int j=0; j<MAX_CPU_COUNT; j++)
SetEvent(StartEvent[j]);
WaitForSingleObject(hEvent[0], INFINITE );
for (int j=0; j<MAX_GPU_COUNT; j++)
ResetEvent(hEvent[j]);
std::cout<<glob_temp_var; //////////////// point 2
}
for (int j=0; j<MAX_CPU_COUNT; j++){
ResetEvent(StartEvent[j]);
ResetEvent(hEvent[j]);
}
CUT_EXIT(argc, argv);
}