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:
#include
#include
#include
#include
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 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
- exception_ptr is a shared pointer-like type, so it is crucial to ensure that at least one exception_ptr is pointing to each exception to prevent them from being released.
- Microsoft-specific: When using SEH exceptions with the /EHa compiler flag, the example code may also capture SEH exceptions like access violations. This may not be desirable in all cases.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3