0
static void timer_start(std::function<void(void)> func, unsigned int interval)
{
  
  std::thread([func, interval]()
  { 
    while (true)
    { 
      auto x = std::chrono::steady_clock::now() + std::chrono::milliseconds(interval);
      func();
      std::this_thread::sleep_until(x);
    }
  }).detach();
}

static void interfacetoBackend()
{ 

}

int main(){
    timer_start(interfacetoBackend, 2000);  

}

I have a timer calling a function at regular interval as shown above. I like to stop before the program end. Currently, I can't stop the timer. How can I stop the timer call?

batuman
  • 7,066
  • 26
  • 107
  • 229
  • Use an `std::atomic` variable to "signal" from main thread when the timer shall exit and check this in your interval at each iteration. FYI: [SO: Multithreading program stuck in optimized mode but runs normally in -O0](https://stackoverflow.com/a/58516119/7478597) – Scheff's Cat Aug 29 '20 at 13:20
  • Btw. a detached thread is not joinable. If you don't detach it, you may join it (`std::thread::join()`) after you "signaled" exiting (or the timer was due). – Scheff's Cat Aug 29 '20 at 13:32

0 Answers0