Reputation: 77
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.
Upvotes: 4
Views: 2568
Reputation: 5469
I'm not sure what's wrong with what you have here. You've created a thread that updates a member variable timer
forever 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:
HANDLE hStdIn = GetStdHandle( STD_INPUT_HANDLE );
while ( true ) {
if ( WAIT_OBJECT_0 == WaitForSingleObject( hStdIn, 1000 ) ) {
// read input
INPUT_RECORD inputRecord;
DWORD events;
if ( ReadConsoleInput( hStdIn, &inputRecord, 1, &events ) ) {
if ( inputRecord.EventType == KEY_EVENT ) {
printf( "got char %c %s\n",
inputRecord.Event.KeyEvent.uChar.AsciiChar,
inputRecord.Event.KeyEvent.bKeyDown ? "down" : "up" );
}
}
}
printf( "update clock\n" );
}
Upvotes: 1
Reputation: 25053
I'm afraid you've misunderstood how the system timers work and how to use them - the whole point is that they automatically run in the background, so you don't have to do your own thread management.
This has examples and explanations of Windows timers in general, and you can use it if you're trying to roll your own Timer
class: Timers Tutorial
This is the Timer
class that comes with Windows.NET, with a code example at the bottom: Timer Class
Edited to add:
Here's a version of the Win32 timer example (from the turorial page) adapted for a non-MFC app:
int nTimerID;
void Begin(HWND hWindow_who_gets_the_tick)
{
// create the timer to alert your window:
nTimerID = SetTimer(hWindow_who_gets_the_tick, uElapse, NULL);
}
void Stop()
{
// destroy the timer
KillTimer(nTimerID);
}
See MSDN: Timer functions for details.
Then inside your window procedure, you get the WM_TIMER
message and respond as you like.
Alternatively, the timer can call a user-defined procedure. See SetTimer function for details.
Upvotes: 0