我不明白爲什麼這個簡單的代碼段有一個死鎖:的std ::的Thread.join()的僵局
#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;
}
編輯 我打字錯誤的contstructor設置MEXIT =真
編輯2 我正在使用msvc2012和v110_xp工具集。
編輯3 問題消失,如果我明確地內主要
'mExit = false' ?? –
我輸錯了,抱歉。問題依然存在。 –
嗯。在你正確使用原子之前,這可能不會變好。並使用調試器來找出線程正在做什麼。在雜草中關閉的可能性相當大,阻止了一些操作系統調用,而不是一次又一次地燃燒100%核心檢查退出條件。 –