Question : How do you make a timer tick in the background? That is the thread that create the timer thread can still do something else while clock is ticking.
Attempt:
-Using _beginthreadex() –> It seems to have race condition
class Timer{
...
static unsigned __stdcall tick(void *param){
while(1){
Timer::timer++;
Sleep(Timer::timer*1000);
}
return 1;
}
}
.....
HANDLE time_thread = (HANDLE) _beginthreadex(0, 0, &Timer::tick,0,0,NULL);
...
//test for 20 seconds
//want to do something while the clock is not 20 seconds
//the mainthread here still has to receive input
//What is the proper way to do it?
while (Timer::getTime() != 20){
cout << Timer::getTime()
}
CloseHandle(time_thread);
...
NOTE: Iam using Visual Studio 2008, not 11 so I do not have C++11 support.
I’m not sure what’s wrong with what you have here. You’ve created a thread that updates a member variable
timerforever and your main use of it is a tight/fast loop that prints (presumably) that time until it reaches 20. What is it not doing? Technically there’s a race condition of incrementing that value versus checking it in another thread, but for the purposes of this example it should be fine…EDIT: try this for non-blocking input with full input control: