【发布时间】:2017-08-11 12:48:30
【问题描述】:
我有一个非常简单的程序:
#include <iostream>
#include <string>
#include <thread>
using namespace std;
struct N{
string s;
N(){}
~N(){cout<<"N dtor"<<endl;}
};
void f(){
N n;
throw 0;
}
int main(){
try{
thread a(f), b(f);
a.join();
b.join();
}catch(exception& e){
cout<<e.what()<<endl;
}
return 0;
}
在我的mac+clang环境下,运行结果是:
libc++abi.dylib: terminating with uncaught exception of type int
Abort trap: 6
它没有像我预期的那样打印“N dtor”。所以我的问题是,如果 std::thread 函数抛出异常,如何捕获/处理它?无法保证线程函数内的代码不会抛出任何异常。
我在linux上试了一下,可以捕获异常并打印:
Enable multithreading to use std::thread: Operation not permitted
非常感谢。
【问题讨论】:
-
如果要将异常传输到调用线程,请使用
std::async。
标签: multithreading c++11 exception dynamic throw