Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I make std::thread not struck the pragma?

I want to design a timer class, there is a function, which sleep some seconds, then call other function.

please see the code:

#include <thread>
#include <iostream>

void func() { printf("timer thread function called\n"); }

class Timer {
 public:
  template <typename Fn> 
  void sleep_start(int sec, const Fn& f) {
    printf("sleep %d\n", sec);
    td_ = std::thread([sec, f]() { std::this_thread::sleep_for(std::chrono::seconds(sec)); f(); }); 
    if (td_.joinable()) td_.join();
  }
  std::thread td_;
};

class A { 
 public:
  void start() {
    t_.sleep_start(10, func);
    printf("start function\n");
  }
  Timer t_; 
};

int main() {
  A a;
  a.start();
}

this code can work well, but the sleep_start function stuck the program.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

the real output is:

sleep 10
timer thread function called
start function

the ideal output is:

sleep 10
start function
timer thread function called

could you help on this? how to make the thread function not struck the program?

>Solution :

You call td_.join() early, sleep_start does not exit until thread finishes.

class Timer {
 public:
  template <typename Fn> 
  void sleep_start(int sec, const Fn& f) {
    printf("sleep %d\n", sec);
    td_ = std::thread([sec, f]() { std::this_thread::sleep_for(std::chrono::seconds(sec)); f(); }); 
  }
  ~Timer() {
    if (td_.joinable()) td_.join();
  }
  std::thread td_;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading