How to organize information exchange between threads about an exceptional situation?
sobes.tech AI
Answer from AI
Several approaches can be used for exchanging information between threads about an exception in C/C++:
-
Shared flag with synchronization: one thread sets a flag (e.g.,
std::atomic<bool>), signaling a problem, and another thread checks this flag. -
Using condition variables (
std::condition_variable): the thread that detects an exception notifies other threads via a condition variable. -
Passing exceptions through special structures: for example, storing an exception object in a shared location and signaling its presence.
-
Using
std::promiseandstd::future: the thread where the exception occurs sets the exception in astd::promise, and another thread retrieves it via astd::future.
Example with std::promise:
#include <iostream>
#include <thread>
#include <future>
void worker(std::promise<void> prom) {
try {
// Some work that may throw an exception
throw std::runtime_error("Error in thread");
} catch (...) {
prom.set_exception(std::current_exception());
}
}
int main() {
std::promise<void> prom;
std::future<void> fut = prom.get_future();
std::thread t(worker, std::move(prom));
try {
fut.get(); // Exception from worker thread will be thrown here
} catch (const std::exception& e) {
std::cout << "Caught exception from thread: " << e.what() << std::endl;
}
t.join();
return 0;
}
This method allows safe transfer of exceptions between threads.