函数静态变量析构函数和线程
function static variable destructor and thread
我有一个简单的程序。
int main()
{
std::atomic<bool> b = true;
ConcurrentQueue<std::string> queue;
std::thread thread( [&]{
while ( b ) {
auto str = queue.wait_and_pop();
std::cout << *str;
}
});
b = false;
queue.push( "end" );
thread.join();
}
ConcurrentQueue<T>
是我自己的线程安全队列实现,wait_and_pop
是使用 std::condition_variable
的阻塞操作。
该程序成功打印"结束"并退出,这里没有问题。(有一个错误,b
启动时thread
为假,导致它立即退出,但这在这里无关紧要(
但是如果我把所有这些包装在一个类中
class object {
public:
object() {
b = true;
thread = std::thread( [this]{
while ( b ) {
auto str = queue.wait_and_pop();
std::cout << *str;
}
});
}
~object() {
b = false;
queue.push( "end" );
thread.join();
}
private:
std::atomic<bool> b;
std::thread thread;
ConcurrentQueue<std::string> queue;
};
并有一个函数静态变量,如
object & func() {
static object o;
return o;
}
和主要
int main() {
object & o = func();
}
现在程序打印"结束",然后卡在第 thread.join()
行的 o
析构函数上。
我已经用叮当测试过了,没问题。这似乎只发生在VC11中。为什么?
最近有一个线程有同样的问题,但我再也找不到了。
基本上,当您有一个静态生存期对象尝试在其析构函数中结束线程时,VS 的运行时库中会出现死锁。
相关文章:
- 如何在调用析构函数时优雅地停止/销毁带有阻塞调用C++线程?
- 为什么即使调用了析构函数,C++11 中的分离线程也可以执行
- 如何正确取消析构函数中的 Boost deadline_timer(在多线程环境中)?
- 析构函数和线程安全
- C++使用函数对象的线程,如何调用多个析构函数而不是构造函数?
- C++ std::线程调用方法,从对象原因到调用此类的析构函数
- 在不同的线程中调用向量析构函数或清除
- 对象析构函数在多线程处理时不断被调用,但该对象并未超出范围
- C++11 线程:在构造函数中启动并在析构函数中加入
- 从析构函数停止线程的正确方法
- boost::shared_ptr的析构函数阻止了唯一的线程
- Qt 线程,来自 QObject 的析构函数的崩溃移动
- 在成员函数上启动线程时不需要的析构函数调用
- std::线程在vc++中的析构函数中获取异常中止
- 在纯虚拟类的析构函数中等待线程死亡会导致运行时错误
- 多个线程调用exit()时的安全静态析构函数
- std::C++11中的线程,如何确保线程在析构函数中完成
- 全局变量构造函数/析构函数是否需要线程保护
- 如何安全地删除析构函数中的线程指针
- VS CTP 14的std::线程析构函数崩溃