Home >Backend Development >C++ >How Can Exceptions be Propagated Between Threads in C ?

How Can Exceptions be Propagated Between Threads in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 04:14:02669browse

How Can Exceptions be Propagated Between Threads in C  ?

Exception Propagation Between Threads

In multithreaded applications, it's important to handle exceptions that occur in worker threads without crashing the entire application. This article explores how to propagate exceptions from worker threads to the main thread, allowing the caller to handle them gracefully.

Challenges of Exception Propagation

One naive approach is to catch exceptions in worker threads and record their type and message. However, this method is limited to a specific set of exception types and requires manual code modifications when adding new exceptions.

Exception Propagation Using exception_ptr

C 11 introduces the exception_ptr type, which provides a safe and flexible way to store and transport exceptions between threads. In this approach:

  1. Each worker thread catches exceptions and stores them in an exception_ptr.
  2. The main thread checks the exception_ptrs to see if any exceptions occurred.
  3. If an exception is found, the main thread rethrows it, allowing the caller to handle it.

Code Example

<code class="cpp">#include <iostream>
#include <thread>
#include <exception>
#include <stdexcept>

static std::exception_ptr myException;

void f() {
    try {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        throw std::runtime_error("To be passed between threads");
    } catch (...) {
        myException = std::current_exception();  // Store the exception
    }
}

int main() {
    std::thread myThread(f);
    myThread.join();

    if (myException) {
        try {
            std::rethrow_exception(myException);  // Rethrow the exception
        } catch (const std::exception& ex) {
            std::cerr << "Thread exited with exception: " << ex.what() << "\n";
        }
    }

    return 0;
}</code>

Multi-Thread Considerations

In scenarios with multiple worker threads, it's necessary to use an array of exception_ptrs to capture exceptions from each thread. Additionally, exception_ptrs are shared pointers, so it's crucial to ensure that at least one exception_ptr points to each exception to prevent premature deallocation.

The above is the detailed content of How Can Exceptions be Propagated Between Threads in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn