我期望子執行緒的狀態,無論它們成功與否,都不應該使主執行緒崩潰。
所以我做了一個快速測驗:
#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;
}
運行結果是:
1
Program stderr
terminate called after throwing an instance of 'int'
好吧,似乎throw 1呼叫導致主執行緒崩潰。我認為對于 c ,每個執行緒都有自己的運行時堆疊和例外行程鏈。
那為什么在我的情況下,子執行緒例外會終止主執行緒?
謝謝。
uj5u.com熱心網友回復:
確實,例外處理本地化為單個執行緒,但與往常一樣,根本不捕獲例外會導致呼叫std::terminate,這反過來會終止整個程式。這同樣適用于導致呼叫的其他條件std::terminate,例如在堆疊展開期間從解構式拋出或讓例外轉義noexcept函式。這些都被認為是不可恢復的錯誤。
例如std::async,如果您需要在執行緒中出現未處理的例外后繼續執行,則可以使用。std::async包括捕獲否則未捕獲的例外并將它們存盤/轉發到 a 中的功能std::future,以便主執行緒可以接收它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/512988.html
標籤:C 多线程例外碰撞扔
上一篇:阻止JS創建例外物件
下一篇:在laravel中搜索多個表
