函数静态变量析构函数和线程 [英] 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
。
ConcurrentQueue<T>
is my own implementation of thread safe queue, wait_and_pop
is a blocking operation that use std::condition_variable
.
此程序成功打印结束并退出,这里没有问题。 (当线程
启动时,有一个错误, b
为false,导致它立即退出, )
this program successfully prints "end" and exits, no problem here. ( there is a bug that b
is false when thread
started which cause it to exit immediately but that is not relevant here )
但是如果我将所有这些包装在一个类中
But if I wrap all these in a class
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;
};
并且有一个函数静态变量,例如
and have a function static variable like
object & func() {
static object o;
return o;
}
和主
int main() {
object & o = func();
}
现在程序打印结束,然后停在析构函数 o
在 thread.join()
。
now the program prints "end" then stuck at destructor of o
at line thread.join()
.
与ang和没有问题。这似乎只发生在VC11。这是为什么?
I have tested this with clang and no problem. This seem to only happen in VC11. Why is that?
推荐答案
最近有一个线程有相同的问题,但我找不到了。
There recently was a thread with the same problem, but I can't find it anymore.
基本上,当你有一个静态生命周期对象试图在它的析构函数中结束一个线程时,在VS的运行时库中有一个死锁。
Basically, there's a deadlock in VS's runtime library when you have a static lifetime object that tries to end a thread in its destructor.
这篇关于函数静态变量析构函数和线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!