函数静态变量析构函数和线程

function static variable destructor and thread

本文关键字:线程 析构函数 变量 静态 函数      更新时间:2023-10-16

我有一个简单的程序。

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 的运行时库中会出现死锁。