Home > Article > Backend Development > How do you propagate exceptions between threads in C using `exception_ptr`?
Propagating Exceptions Between Threads in C
The task of propagating exceptions between threads in C arises when a function called from a main thread spawns multiple worker threads for CPU-intensive work. The challenge lies in handling exceptions that may occur on the worker threads and propagating them back to the main thread for proper handling.
Conventional Approach
One common approach is to manually catch a variety of exceptions on worker threads, record their details, and rethrow them on the main thread. However, this method has a limitation in that it supports only a fixed set of exception types. Any new exception types introduced in the future would require manual modification to the code.
C 11 Exception Handling
C 11 introduces the exception_ptr type, providing a more robust solution for exception propagation. This type allows for the transportation of exceptions between threads.
Example Implementation
The following example demonstrates how to propagate exceptions using exception_ptr:
<code class="cpp">#include <iostream> #include <thread> #include <exception> #include <stdexcept> static std::exception_ptr eptr; void worker() { try { // Simulated CPU-intensive work with a delay std::this_thread::sleep_for(std::chrono::seconds(1)); throw std::runtime_error("Exception in worker thread"); } catch (...) { eptr = std::current_exception(); } } int main() { // Create a worker thread std::thread workerThread(worker); workerThread.join(); // Check if an exception occurred on the worker thread if (eptr) { try { // Rethrow the exception on the main thread std::rethrow_exception(eptr); } catch (const std::exception &ex) { // Handle the exception on the main thread std::cerr << "Worker thread exited with exception: " << ex.what() << "\n"; } } return 0; }</code>
In this example, the worker thread catches any exception that occurs and assigns it to eptr. On the main thread, the eptr is checked and, if an exception is present, it is rethrown.
Note for Multiple Worker Threads
If you have multiple worker threads, you will need to maintain separate exception_ptr instances for each thread to capture any potential exceptions.
Additional Considerations
The above is the detailed content of How do you propagate exceptions between threads in C using `exception_ptr`?. For more information, please follow other related articles on the PHP Chinese website!