C++ std::thread 多線程中的異常處理


環境:

VS2019

包含頭文件:

#include <iostream>
#include<thread>
#include<exception>

線程函數采用try{...}catch(...){...}機制

如果需要在主線程檢測子線程的異常時,采用全局變量的方式獲取

std::exception_ptr ptr;
void f0()
{
  try {
    std::string str;
    for (int i = 0; i < 5; i++)
    {
      std::cout << "f0線程啟動" << i << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
    str.at(2);  //越界訪問
    throw std::exception("線程中正常拋出異常");  //拋出異常
    }
  catch (const std::exception& m) {
    std::cout <<"子線程輸出異常信息:" << m.what() << std::endl;
    ptr = std::current_exception();
    }
}
int main()
{
  std::thread t1(f0);
  t1.join();  //主線程等待子線程結束
  try {
  if (ptr) {
    std::cout << "檢測到子線程異常" << std::endl;
    std::rethrow_exception(ptr);
    }
   }
  catch (std::exception& e)
  {
    std::cout <<"主線程輸出子線程錯誤信息:" << e.what() << std::endl;
  }
  std::cout << "主線程退出!" << std::endl;
  return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM