#include <iostream>
#include <thread>
#include <future>
#include <stdexcept>
void asyncDivision(std::promise<double>&& p, double num, double den) {
if (den == 0.0) {
// We cannot return an exception, we must store it in the promise
p.set_exception(std::make_exception_ptr(std::runtime_error("Division by zero error!")));
} else {
// Calculation successful, store the value
p.set_value(num / den);
}
}
int main() {
double num = 10.0;
double den = 0.0; // Change to 2.0 to see success case
// 1. Create the promise
std::promise<double> divPromise;
// 2. Get the future associated with this promise
std::future<double> divResult = divPromise.get_future();
// 3. Launch thread, moving the promise into it
std::thread t(asyncDivision, std::move(divPromise), num, den);
try {
std::cout << "Waiting for result...\n";
// 4. Block and wait. If the thread set an exception, it is thrown here
double result = divResult.get();
std::cout << "Result: " << result << "\n";
} catch (const std::exception& e) {
// 5. Catch the exception propagated from the background thread
std::cout << "Caught exception from thread: " << e.what() << "\n";
}
t.join(); // Always join manual threads
return 0;
}