问题描述
在c++标准库std::thread的使用过程中,遇到一个程序必现的Abort()问题,这里跟大家分享以下(以下代码仅为示例程序,项目代码无法分享):
报错提示:
示例代码:
#include <iostream>
#include <thread>
void f1(int n)
{
std::cout << "thread " << n << std::endl;
}
void thread_example()
{
std::thread t1;
t1 = std::thread(f1, 1);
//t1.join();//Trap: if a thread variable doesn't call "detach" or "join", its destructor will call "terminate" to abort program
}
int main()
{
thread_example();
system("pause");
return 0;
}
注意上述注释掉的行,是为了复现遇到的问题才做的。
原因分析:
这里的问题就在于使用了std::thread, 但是在该类的实例被销毁前没有调用该类的detach()函数或者join()函数,根据std::thread的用法说明,上述两个方法都没有调用,std::thread的析构函数就会调用terminate()函数,整个程序就会被终止,也就出现了上面的报错信息。
解决方案:
在合适的代码位置根据需要调用std::thread的detach()或者join()函数即可。
(示例程序中去掉注释行的注释,即调用join()函数即可保证程序正常结束)