std :: thread在vc ++的析构函数中得到异常中止 [英] std::thread get abort exception in destructor in vc++
问题描述
这是我的示例测试程序。
#includestdafx.h
#include< thread>
#include< Windows.h>
类ThreadTest
{
public:
ThreadTest()
{
}
〜ThreadTest
{
}
void ThreadProc()
{
}
};
int _tmain(int argc,_TCHAR * argv [])
{
ThreadTest test;
std :: thread t = std :: thread(& ThreadTest :: ThreadProc,std :: ref(test));
睡眠(5000);
return 0;
}
我在nativate pthread_create函数中有经验,但似乎缺少某些东西。当我把Sleep(15000);在ThreadProc方法中,同样的问题没有任何变化。
std :: thread
的析构函数:如果一个线程在它是可加入的时被销毁, std :: terminate
被调用。
从C ++ 11标准草案n3290(§30.3.1.3线程析构函数):
如果
joinable / code>然后
terminate()
,否则没有效果。 [注意:在其析构函数中隐式分离或加入joinable()线程可能导致难以调试正确性(对于分离)或性能(对于加入)错误,只有当异常出现时才会遇到。因此,程序员必须确保在线程仍然可连接的时候析构函数不会被执行。 - end note]
您必须加入会话串或分离会话串。在你的情况下,加入似乎是正确的选择。
I am getting abort exception in simple VC++ program when main method completes.
Here is my sample test program.
#include "stdafx.h"
#include <thread>
#include <Windows.h>
class ThreadTest
{
public:
ThreadTest()
{
}
~ThreadTest()
{
}
void ThreadProc()
{
}
};
int _tmain(int argc, _TCHAR* argv[])
{
ThreadTest test;
std::thread t = std::thread(&ThreadTest::ThreadProc, std::ref(test));
Sleep(5000);
return 0;
}
I have experience in nativate pthread_create functions but it seems that something is missing. When I put Sleep(15000); in ThreadProc method same issue happens without any changes.
This is documented in std::thread
's destructor: if a thread is destroyed while it is joinable, std::terminate
is called.
Quote from the C++11 standard draft n3290 (§30.3.1.3 thread destructor):
If
joinable()
thenterminate()
, otherwise no effects. [ Note: Either implicitly detaching or joining a joinable() thread in its destructor could result in difficult to debug correctness (for detach) or performance (for join) bugs encountered only when an exception is raised. Thus the programmer must ensure that the destructor is never executed while the thread is still joinable. — end note ]
You must either join the thread, or detach it. Joining seems like the right option in your case.
这篇关于std :: thread在vc ++的析构函数中得到异常中止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!