我有一个简单的程序。
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
.
该程序成功打印“end”并退出,这里没有问题。 (有一个错误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;
}
and main
int main() {
object & o = func();
}
现在程序打印“end”然后卡在析构函数o
在线thread.join()
.
我已经用 clang 测试过了,没有问题。这似乎只发生在VC11中。这是为什么?
最近有一个帖子有同样的问题,但我找不到了。
基本上,当您有一个静态生命周期对象试图在其析构函数中结束线程时,VS 的运行时库中就会出现死锁。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)