How to make Windows Timer work in the background thread

Question: How to make a timer in the background? That is, the thread creating the timer thread can still do something else while the clock is ticking.

Attempt: -Using _beginthreadex () β†’ It seems that the 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. I am using Visual Studio 2008, not 11, so I do not have support in C ++ 11.

+4
source share
2 answers

I'm not sure what happened to what you have here. You have created a thread that updates the timer member variable forever, and its main use is a closed / fast loop that prints (presumably) this time until it reaches 20. What does it not? Technically, there is a race condition that increases this value compared to checking it in another thread, but for the purposes of this example it should be good ...

EDIT: try this for non-blocking login 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" ); } 
+1
source

I’m afraid that you misunderstood how system timers work and how to use them - the thing is that they automatically start in the background, so you don’t need to do your own thread control.

There are examples and explanations of Windows timers in general, and you can use them if you are trying to flip your own Timer : Timers Tutorial class

This is the Timer class that ships with Windows.NET, with sample code below: Timer Class

Edited to add:

Here is an example Win32 timer example (from the page from the tour.), Adapted for an application other than MFC:

 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 more information.

Then, inside your window procedure, you will receive a WM_TIMER message and reply as you like.

Alternatively, a timer may invoke a user procedure. See the SetTimer function for more details .

0
source

Source: https://habr.com/ru/post/1447008/


All Articles