c++

c++线程异常处理该如何做

小樊
83
2024-10-16 10:37:06
栏目: 编程语言

在C++中,线程的异常处理与主线程的异常处理略有不同。因为每个线程都有自己的运行栈,所以当线程抛出异常时,该异常不会直接传递给主线程。为了处理线程中的异常,我们需要在线程函数内部捕获异常,并将其存储在一个线程局部存储(Thread Local Storage, TLS)变量中,然后在线程函数结束之前将其传递给主线程。

以下是一个简单的示例,展示了如何在C++线程中捕获异常并将其传递给主线程:

#include <iostream>
#include <thread>
#include <stdexcept>
#include <mutex>

std::mutex mtx;
thread_local std::exception_ptr threadExceptionPtr;

void threadFunction() {
    try {
        // 在这里执行你的线程代码
        throw std::runtime_error("An error occurred in the thread.");
    } catch (...) {
        threadExceptionPtr = std::current_exception();
    }
}

int main() {
    std::thread t(threadFunction);

    t.join();

    if (threadExceptionPtr) {
        try {
            std::rethrow_exception(threadExceptionPtr);
        } catch (const std::exception& e) {
            std::lock_guard<std::mutex> lock(mtx);
            std::cerr << "Caught exception in main thread: " << e.what() << std::endl;
        }
    }

    return 0;
}

在这个示例中,我们定义了一个名为threadFunction的线程函数,它使用try-catch块捕获异常。如果线程抛出异常,我们将异常指针存储在threadExceptionPtr中。在线程函数结束后,我们通过调用join()等待线程完成。然后,我们检查threadExceptionPtr是否包含异常指针。如果包含,我们使用std::rethrow_exception()重新抛出异常,并在catch块中捕获它。最后,我们使用互斥锁保护输出,以防止多个线程同时输出异常信息。

0
看了该问题的人还看了