c++11线程:子线程抛出异常导致主线程崩溃

Imm*_*ant 1 c++ crash multithreading exception throw

我期望子线程的状态,无论成功与否,都不应该使主线程崩溃。

所以我做了一个快速测试:

#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;
}
Run Code Online (Sandbox Code Playgroud)

运行结果为:

1
Program stderr
terminate called after throwing an instance of 'int'
Run Code Online (Sandbox Code Playgroud)

好吧,看来throw 1调用会导致主线程崩溃。我认为对于 C++,每个线程都有自己的运行时堆栈和异常进程链。

那为什么在我的例子中,子线程异常会终止主线程呢?

谢谢。

use*_*522 5

确实,异常处理被本地化到单个线程,但与往常一样,根本不捕获异常会导致调用std::terminate,从而终止整个程序。这同样适用于导致调用 的其他条件std::terminate,例如在堆栈展开期间从析构函数抛出或让异常逃逸函数noexcept。这些都被认为是不可恢复的错误。

std::async如果您需要在线程中出现未处理的异常后继续执行,您可以使用eg 。std::async包括捕获未捕获的异常并将其存储/转发到 a 中的功能std::future,以便主线程可以接收它们。