#include #include #include #include using namespace std ; // Function executed in a separate thread void calculate_sum(int a1, int b1, promise& promise_obj) { cout << "Worker thread: Calculating sum..." << endl; // Simulate some long work this_thread::sleep_for(chrono::seconds(2)); int sum = a1 + b1 ; // Fulfill the promise by setting the value promise_obj.set_value(sum); cout << "Worker thread: Value set." << endl ; this_thread::sleep_for( chrono::seconds(20) ) ; cout << "Exiting calculate_sum" << endl ; } int main() { // 1. Create a promise object for an integer result promise promise_obj; // 2. Get the associated future object from the promise future future_obj = promise_obj.get_future() ; // 3. Launch a worker thread, passing the promise object by reference thread worker_thread(calculate_sum, 5, 10, ref(promise_obj)) ; // 4. In the main thread, wait for the result using the future cout << "Main thread: Waiting for the result..." << endl; // get() blocks the current thread until the promise has a value //However int result = future_obj.get(); cout << "Main thread: Retrieved result is: " << result << endl; // Join the worker thread to the main thread worker_thread.join(); cout << "End of main: " << endl; return 0; }