J'ai un programme très simple:C++ 11: Clang sur Mac n'attrape pas les exceptions lancées par la fonction std :: thread?
#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;
}
Sur mon environnement mac + clang, le résultat est en cours d'exécution:
libc++abi.dylib: terminating with uncaught exception of type int
Abort trap: 6
Il n'imprime pas le "N dtor" que je attendu. Donc ma question, si la fonction std :: thread renvoie une exception, comment l'attraper/gérer? Il n'y a aucune garantie que le code dans une fonction thread ne jette aucune exception.
Je l'ai essayé sur linux, et l'exception pourrait être pris et imprimer:
Enable multithreading to use std::thread: Operation not permitted
Merci beaucoup.
Si vous souhaitez transporter l'exception vers le thread appelant, utilisez 'std :: async'. – ecatmur