There is a function that changes the value "bIsTrue" to true after 2sec. When bIsTrue is "true", the main thread can escape while loop and print out "Now bIsTrue is True!" in main()
#include <iostream>
#include <process.h>
#include <Windows.h>
using namespace std;
bool bIsTrue; // global variable
unsigned __stdcall Func(void* pArg)
{
Sleep(2000);
bIsTrue = true;
return 0;
}
and this is main(). but when there is nothing in while loop, the main thread do not print "Now bIsTrue is True!" in release mode.
int main()
{
// bIsTrue will be "true" after 2sec.
bIsTrue = false;
HANDLE tHandle = (HANDLE)_beginthreadex(NULL, 0, Func, NULL, 0, NULL);
CloseHandle(tHandle);
size_t i = 0;
while (!bIsTrue)
{
// If here is a nothing, main thread can't escape this loop in Release mode.
// but can escape in Debug mode.
// When here is Sleep() or cout, main thread can escape this loop in both mode.
// Sleep(1000);
// OR
// cout << i++ << endl;
}
cout << "Now bIsTrue is True!" << endl;
return 0;
}
this is the result when print 'i' in the loop.
Can you guys understand why I got this result?