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:
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!