简体   繁体   中英

c++11 thread: sub-thread throws exception leads to main thread crash

I was expecting that the status of sub-thread, whether they succeed or not, should not crash main thread.

So I had a quick test:

#include <thread>
#include <iostream>
#include <exception>
using namespace std;
using namespace std::chrono;
void th_function() {
    this_thread::sleep_for(chrono::seconds(2));
    throw 1; // the criminal here!
}
int main() {
    auto th = thread{ th_function };
    this_thread::sleep_for(chrono::seconds(1));
    cout << "1" << endl;
    th.join();
    cout << "2" << endl;
    return 0;
}

The running result is:

1
Program stderr
terminate called after throwing an instance of 'int'

Well, seems the throw 1 call leads to main thread crash. I think for c++, each thread has its own runtime stack and exception-process chain.

Then why in my case, sub-thread exception will terminate main thread?

Thanks.

It is true that exceptions handling is localized to a single thread, but as always, not catching an exception at all causes a call to std::terminate , which in turn terminates the whole program. The same applies to other conditions resulting in a call to std::terminate , eg throwing from a destructor during stack unwinding or letting an exception escape a noexcept function. These are all considered unrecoverable errors.

You can use eg std::async if you need to continue execution after an unhandled exception in the thread. std::async includes functionality to catch otherwise uncaught exceptions and stores/forwards them in a std::future , so that the main thread can receive them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM