Search⌘ K
AI Features

Solution: Promise to Deliver

Explore the use of std::promise in C++ to transfer ownership, communicate results between threads, and handle exceptions effectively. Understand how to synchronize threads using futures, manage exceptions across thread boundaries, and ensure proper thread cleanup to build safe and efficient concurrent programs.

We'll cover the following...
C++ 23
#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;
}
...