【发布时间】:2016-10-22 19:49:00
【问题描述】:
如何在 Bar 的析构函数中终止我的分离线程(无需等到线程从睡眠中醒来)?
class Bar {
public:
Bar() : thread(&Bar:foo, this) {
}
~Bar() { // terminate thread here}
...
void foo() {
while (true) {
std::this_thread::sleep_for(
std::chrono::seconds(LONG_PERIOD));
//do stuff//
}
}
private:
std::thread thread;
};
【问题讨论】:
-
你能在定时条件等待而不是硬睡眠的情况下入睡吗?
-
您可以将
while (true) {更改为while (isDone) {,其中isDone是atomic<bool>变量的成员。 -
@ NathanOliver 但是如果我分离它并且线程访问 Bar 的成员字段,则在 Bar 实例被破坏后行为将是未定义的
-
@user695652:您必须等待,直到
LONG_PERIOD超时。但是,使用条件变量,您可以阻止线程此后执行任何工作。虽然这解决了您之前的问题的一半,但您现在已经创建了一个新问题:您怎么知道您的线程在与数据分离时不在处理数据的中间?也许您可以提出一个基于弱指针的解决方案(在Bar销毁时失效)。
标签: c++ multithreading c++11