【发布时间】:2013-09-03 14:35:59
【问题描述】:
struct Test {
bool active{true};
void threadedUpdate() {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
if(!active) // crashes here after Test instance is destroyed
return;
}
Test() {
std::thread([this]{ while(true) threadedUpdate(); }).detach();
}
~Test() {
// somehow stop the detached thread?
}
};
当Test 的实例被初始化时,它会生成并分离一个在后台运行的std::thread。当同一个实例被销毁时,前面提到的线程会尝试访问 active 成员,该成员与实例一起被销毁,导致崩溃(以及 AddressSanitizer 回溯)。
有没有办法停止~Test() 上的分离线程?
设计很糟糕。 在调用者被销毁之前在后台运行的线程应该如何正确生成/处理?
【问题讨论】:
-
作为一般规则,您不应该分离线程,除非该线程控制它正在使用的任何资源的生命周期。该线程使用
Test,但不控制其生命周期,因此不应分离。
标签: c++ multithreading c++11 detach stdthread