0

I am trying to do timer function that refresh every 1 second for special events. The problem is that if i used while + Sleep(1000) or for loop + Sleep(1000), it doesn't load the other functions under it, so I am looking for solution.

I tried the following:

void Timer(){
  while(true){
    // events
    if(Get_Current_Minute == Event_Minute)
      // do event
      Sleep(1000);
  }
}

int Main(){

  std::cout << " Hello " << std::endl; // loaded
  Function() // loaded;

  Timer(); // the timer function

  std::cout << " Other functions " << std::endl; // not loaded
  Function_2() // not loaded
}

So what can be the solution? I want to load everything in my application + there be a timer refresh every 1 second for the events.

Ryan Stein
  • 7,930
  • 3
  • 24
  • 38
Metay Jack
  • 53
  • 1
  • 11

1 Answers1

1

you execute function Timer()

  • which is infinite loop
  • so it will never continue to your Function_2();

if you want to implement this as it is then Timer(); should be

  • separate thread
  • or real OS Timer event (without Sleep or loop)

If you cant/dont want to go this way

  • then you must merge Function_2() and Timer() together.
  • In that case do not use Sleep
  • but measure real time and if it is bigger then planed event time
  • execute it and plan next event time

Thread example:

//---------------------------------------------------------------------------
volatile int  threads_run=0;
volatile bool threads_stop=false;
unsigned long __stdcall thread_timer(LPVOID p)
    {
    threads_run++;
    for (;threads_stop;)
        {
        //Do your event stuff
        Sleep(1000);
        }
    threads_run--;
    return 0;
    }
void main()
    {
    HANDLE hnd;
    std::cout << " Hello " << std::endl;
    Function();

    // start Timer thread
    hnd=CreateThread(0,0,thread_timer,NULL,0,0);

    std::cout << " Other functions " << std::endl;
    Function_2();

    // stop and wait for all threads
    threads_stop=true;
    for (;threads_run;) Sleep(10);
    }
//---------------------------------------------------------------------------
Spektre
  • 49,595
  • 11
  • 110
  • 380
  • well do not forget to CloseHandle(hnd) when you do not need it anymore (close handle will not terminate the thread) when your app stops it will close it automaticaly but if you dynamicly create many threads then you shoud close their handles your self otherwise you will consume more and more handles until Windows stops working at all (not just your app) PS handles can be used to change affinity or pause/resume/terminate threads – Spektre Dec 13 '13 at 16:17