c++ - std::thread.join() 死锁

标签 c++ multithreading

我不明白为什么这个简单的片段有一个死锁:

#include <atomic>
#include <thread>
#include <memory>

using namespace std;
class Test {
public:

    Test() : mExit( false )
    {
        mThread = thread( bind( &Test::func, this ) );
    }

    ~Test()
    {
        if ( mThread.joinable() )
        {
            mExit = true;
            mThread.join();
        }
    }

private:
    void func() 
    {
        while ( !mExit )
        {
            // do something
        }
    }

private:
    atomic< bool > mExit;
    thread mThread;
};

typedef unique_ptr< Test > TestPtr;
TestPtr gTest;

int main()
{
    gTest = TestPtr( new Test );
    return 0;
}

编辑 我输入了错误的构造函数集 mExit = true

编辑 2 我正在使用带有 v110_xp 工具集的 msvc2012。

编辑 3 如果我在 main

中明确调用 gTest.release() ,问题就会消失

最佳答案

我刚遇到这个问题,所以我发布了其他人的真实答案。

至少在 visual studio 中,有一个“退出锁”,当线程进入退出代码时被锁定(即在主线程的 main() 之后,在 f() 用于 std::thread(f))。

由于您的测试类仅在 main() 完成后才被销毁,因此“退出锁”被锁定。只有这样,您才设置 mExit = true; 并且允许另一个线程完成。这个另一个线程然后等待获得主线程已经占用的“退出锁”,而主线程在 mThread.join(); 中等待导致死锁。

所以是的,您需要在主线程完成之前加入所有线程。

关于c++ - std::thread.join() 死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17191894/

相关文章:

c++ - 四元数到达万向节锁

c++ - 如何在 Linux 中检测系统时间的变化?

java - 不丢弃数据包的距离 vector 线程

c++ - 如何查看我的应用程序是否需要提升权限?

c++ - C++中的复制构造函数

c++ - 使用大型整数对数据集有效地初始化 unordered_map

java - Android服务在强制停止后继续运行

c++ - 为什么从 mmaped 文件构建 std::string 这么慢?

java - 读取套接字响应时,线程在几次迭代后 hibernate

multithreading - 并行算法实现建议