vendredi 11 août 2017

C++11 How to catch exception thrown by std::thread function?

I've got a very simple program as:

#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;
}

On my mac+clang environment, the running result is:

libc++abi.dylib: terminating with uncaught exception of type int
Abort trap: 6

It doesn't print the "N dtor" as I expected. So my question, if std::thread function throws an exception, how to catch/deal with it? There's no guarantee that the code inside a thread function doesn't throw any exception.

Thanks a lot.

Aucun commentaire:

Enregistrer un commentaire