Home > front end >  How can I make std::thread not struck the pragma?
How can I make std::thread not struck the pragma?

Time:09-02

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.

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?

CodePudding user response:

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_;
};
  • Related