我不明白为什么这个简单的片段有一个死锁:
#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/