Handling exceptions in a multithreaded C++ program can be challenging because exceptions thrown in one thread do not propagate to other threads.
Each thread operates independently, so exception handling must be managed within the thread itself. Here’s how you can handle exceptions in a multithreaded environment:
std::promise
and std::future
to pass exceptions from worker threads to the main thread.Here’s an example to illustrate this:
#include <future>
#include <iostream>
#include <stdexcept>
#include <thread>
void Task(std::promise<void>&& promise) {
try {
// Simulate an error
throw std::runtime_error("Something went wrong!");
} catch (...) {
promise.set_exception(std::current_exception());
}
}
int main() {
std::promise<void> promise;
std::future<void> future = promise.get_future();
std::thread t(Task, std::move(promise));
try {
future.get();
} catch (const std::exception& e) {
std::cout << "Exception caught: " << e.what();
}
t.join();
}
Exception caught: Something went wrong!
In this example, the Task
function throws an exception, which is caught and set on the std::promise
. The main
thread retrieves this exception through the std::future
and handles it.
Key points to remember:
std::promise
and std::future
for safe exception communication between threads.This approach ensures that exceptions in worker threads are properly handled and can be communicated back to the main thread or a central exception handler.
Answers to questions are automatically generated and may not have been reviewed.
Multithreading in C++ standard library algorithms using execution policies