在多线程 c++++ 中,异常处理通过 std::promise 和 std::future 机制实现:在抛出异常的线程中使用 promise 对象记录异常。在接收异常的线程中使用 future 对象检查异常。实战案例展示了如何使用 promise 和 future 在不同线程中捕获和处理异常。
如何处理跨线程的 C++ 异常
前言
在多线程编程中,异常可能会在任何线程中抛出。处理跨线程的异常需要额外的考虑,因为对于异常是如何以及在何处抛出的,没有明确的控制。
异常传递机制
C++ 标准库提供了一种传递异常的机制,称为 std::promise 和 std::future。我们可以使用它们来安全地在线程之间传递异常。
std::promise 负责生成异常,而 std::future 负责接收异常。两个对象必须在同一个线程中创建:
// 在主线程创建
std::promise<void> promise;
std::future<void> future = promise.get_future();
当异常在其他线程中抛出时,我们可以使用 promise 对象将其传递:
// 在 worker 线程
try {
// ... 代码可能会抛出异常
}
catch (const std::exception& e) {
promise.set_exception(std::make_exception_ptr(e));
}
然后,可以在主线程中使用 future 对象来检查异常:
// 在主线程
try {
future.get();
}
catch (const std::exception& e) {
// 处理异常
}
实战案例
以下代码展示了如何使用 std::promise 和 std::future 来处理跨线程异常:
#include <iostream>
#include <future>
#include <thread>
// 打印函数以展示在不同线程中抛出的异常
void printFunction() {
try {
throw std::runtime_error("这是一个运行时错误!");
}
catch (const std::exception& e) {
std::cerr << "Worker 线程捕获异常:" << e.what() << 'n';
}
}
int main() {
std::promise<void> promise;
std::future<void> future = promise.get_future();
// 在新线程中运行打印函数
std::thread worker(printFunction);
// 让主线程等待 worker 线程
try {
future.get();
}
catch (const std::exception& e) {
std::cerr << "主线程捕获异常:" << e.what() << 'n';
}
worker.join();
return 0;
}
结论
通过使用 std::promise 和 std::future,我们可以安全地处理跨线程的异常。这使我们能够在异常发生后继续执行,并在以后处理它。