Sobes.tech
Junior — Middle

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++:

  1. Shared flag with synchronization: one thread sets a flag (e.g., std::atomic<bool>), signaling a problem, and another thread checks this flag.

  2. Using condition variables (std::condition_variable): the thread that detects an exception notifies other threads via a condition variable.

  3. Passing exceptions through special structures: for example, storing an exception object in a shared location and signaling its presence.

  4. Using std::promise and std::future: the thread where the exception occurs sets the exception in a std::promise, and another thread retrieves it via a std::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.

How to organize information exchange between threads… - sobes.tech