多线程中未捕获的异常会终止整个程序,因此需在每个线程函数中使用try-catch捕获std::exception等异常,记录日志或通知主线程,防止程序崩溃和资源泄漏。

在C++多线程程序中,异常处理比单线程复杂得多。线程中抛出的异常如果未在该线程内捕获,会导致整个程序调用 std::terminate,即使其他线程仍在运行。因此,多线程环境下的异常协调处理至关重要,必须确保异常被正确传播或记录,避免资源泄漏或程序崩溃。
每个线程的入口函数都应包含顶层异常捕获机制,防止未处理异常导致线程终止并引发整个程序退出。
- 每个线程函数建议使用 try-catch 包裹 - 捕获所有可能异常(如 std::exception 及其派生类) - 可选择记录日志、设置错误状态或通知主线程示例:
void worker_thread() {
try {
// 业务逻辑,可能抛出异常
do_work();
} catch (const std::exception& e) {
std::cerr << "Exception in thread: " << e.what() << std::endl;
// 可通过共享变量或队列通知主线程
}
}
有时需要将子线程中的异常传递给主线程处理。C++ 提供了 std::exception_ptr 来捕获和传递异常对象。
立即学习“C++免费学习笔记(深入)”;
- 使用 std::current_exception() 获取当前异常指针 - 通过共享数据结构(如 promise、队列)传递 exception_ptr - 在接收线程中用 rethrow_exception() 重新抛出示例:使用 std::promise 传递异常
std::promise<int> result_promise;
<p>void worker() {
try {
throw std::runtime_error("Something went wrong");
} catch (...) {
result_promise.set_exception(std::current_exception());
}
}</p><p>int main() {
std::thread t(worker);
t.join();</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">try {
result_promise.get_future().get();
} catch (const std::exception& e) {
std::cout << "Caught exception: " << e.what() << std::endl;
}
return 0;}
C++ 标准不允许一个线程直接抛出异常并由另一个线程捕获。异常栈展开仅在抛出异常的线程内有效。
- 不要试图在 thread A 中 throw,让 thread B catch - 异常传播必须通过显式机制(如 promise、自定义错误通道) - 多线程同步结构(互斥量、条件变量)不会自动处理异常传播错误做法(不可行):
// 错误:不能跨线程 catch 别人抛的异常
std::thread t([]{
throw std::logic_error("No one can catch this directly");
});
t.join(); // 程序终止
使用 std::async 启动任务时,异常会被自动捕获并存储在 shared state 中,通过 future::get() 重新抛出。
- async 返回的 future 可安全捕获异常 - 异常在 get() 调用时 rethrow - 适用于任务型并发模型示例:
auto future = std::async(std::launch::async, []() {
throw std::runtime_error("Error in async task");
});
<p>try {
future.get();
} catch (const std::exception& e) {
std::cout << "Async exception: " << e.what() << std::endl;
}
基本上就这些。多线程异常处理的关键是:不依赖默认行为,主动捕获、传递和处理异常。使用 std::exception_ptr 和 future 等机制,可以实现安全的跨线程错误通知,避免程序意外终止。设计并发系统时,异常协调应作为错误处理方案的一部分提前规划。
以上就是C++异常与并发 多线程异常协调处理的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号