Home > Article > Backend Development > How to Effectively Propagate Exceptions Between Threads in C ?
Propagating Exceptions Between Threads
Introduction:
In multithreaded applications, it is crucial to handle exceptions effectively to prevent unexpected application crashes. When working with multiple threads, exceptions that occur on worker threads should be gracefully propagated back to the main thread for handling, ensuring that the application remains stable.
Solution Using Exception Pointers:
C 11 introduced the concept of exception pointers (exception_ptr), which allow exceptions to be transported across thread boundaries. Exception pointers hold a shared pointer reference to the exception object. Here's an example:
<code class="cpp">#include <thread> #include <exception> std::exception_ptr exceptionPtr; void workerThread() { try { // Perform some task with potential exceptions } catch(...) { exceptionPtr = std::current_exception(); } } int main() { std::thread worker(workerThread); worker.join(); if (exceptionPtr) { try { std::rethrow_exception(exceptionPtr); } catch (const std::exception& ex) { // Handle the exception on the main thread std::cerr << "Exception occurred on worker thread: " << ex.what() << "\n"; } } return 0; }</code>
In this solution, the exception pointer is created on the worker thread and assigned a reference to the caught exception. The main thread then checks if an exception pointer exists and rethrows the exception for handling.
Note:
The above is the detailed content of How to Effectively Propagate Exceptions Between Threads in C ?. For more information, please follow other related articles on the PHP Chinese website!