【发布时间】:2021-10-10 01:25:07
【问题描述】:
我想在 C++ 中设计一个计时器,在固定时间后执行我的功能。
代码喜欢这样:
#include <thread>
typedef void (*callback)();
class timer {
public:
void start(int sec, callback f) {
std::thread t([&sec, &f]() {sleep(sec); f();});
}
};
void test () {
printf("here called\n");
}
int main() {
timer t;
t.start(3, test);
while (1);
}
但是当我运行这段代码时,我得到了:
terminate called without an active exception
[1] 3168208 abort (core dumped) ./a.out
你能帮忙吗?并且,对于更灵活的计时器设计有什么建议吗?
【问题讨论】:
-
sleep纯粹是特定于平台的。我想你在找:std::this_thread::sleep_for(std::chrono::seconds(sec));(包括<chrono>) -
此外,您还有一个问题,
t通过引用捕获sec和callback,但这些是对start本地变量的引用,其生命周期在start返回时立即结束.
标签: c++ multithreading c++11