In multithreaded applications, it is imperative to handle exceptions gracefully to prevent crashes and data corruption. One common scenario is when a main thread spawns worker threads to perform intensive tasks and awaits their results. In such cases, exceptions occurring within the worker threads should be propagated back to the main thread for proper handling.
Propagating Exceptions with exception_ptr
C 11 introduced the exception_ptr type, which enables the transportation of exceptions between threads. Consider the following example:
<code class="cpp">#include <iostream> #include <thread> #include <exception> #include <stdexcept> static std::exception_ptr teptr = nullptr; void f() { try { std::this_thread::sleep_for(std::chrono::seconds(1)); throw std::runtime_error("To be passed between threads"); } catch(...) { teptr = std::current_exception(); } }</code>
The f() function catches any exception and captures it in teptr using std::current_exception().
Retrieving Exceptions on the Main Thread
The main thread retrieves the exception from the worker thread:
<code class="cpp">std::thread mythread(f); mythread.join(); if (teptr) { try{ std::rethrow_exception(teptr); } catch(const std::exception &ex) { std::cerr << "Thread exited with exception: " << ex.what() << "\n"; } }</code>
If an exception was captured (teptr is non-null), std::rethrow_exception() throws the exception on the main thread, allowing the caller to handle it.
Handling Multiple Worker Threads
For scenarios with multiple worker threads, you can have an exception_ptr for each thread to capture exceptions. Additionally, note that exception_ptr is a shared pointer; thus, at least one pointer must always point to an exception to prevent premature deletion.
Caution for Microsoft-Specific Exceptions
If using Structured Exception Handling (SEH) exceptions, the example code will also transport SEH exceptions, which may not be desirable.
The above is the detailed content of How do I propagate exceptions between threads in C ?. For more information, please follow other related articles on the PHP Chinese website!