如何使std::thread不命中杂注



我想设计一个timer类,有一个函数,它会休眠几秒钟,然后调用其他函数。

请查看代码:

#include <thread>
#include <iostream>
void func() { printf("timer thread function calledn"); }
class Timer {
public:
template <typename Fn> 
void sleep_start(int sec, const Fn& f) {
printf("sleep %dn", 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 functionn");
}
Timer t_; 
};
int main() {
A a;
a.start();
}

这个代码可以很好地工作,但是sleep_start函数卡住了程序。

实际输出为:

sleep 10
timer thread function called
start function

理想的输出是:

sleep 10
start function
timer thread function called

你能帮忙吗?如何使线程函数不击中程序?

您提前调用td_.join()sleep_start在线程完成之前不会退出。

class Timer {
public:
template <typename Fn> 
void sleep_start(int sec, const Fn& f) {
printf("sleep %dn", 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_;
};

最新更新