#include #include #include #include #include #include #include #include using namespace std ; int globalResult = -1 ; void calculate_value() { cout << "Calculating value in background...\n"; this_thread::sleep_for( chrono::seconds(5) ) ; // Simulate long computation globalResult = 42 ; } int main() { //Start the thread thread t1( calculate_value ) ; cout << "Main thread continues to execute...\n" ; while ( globalResult == -1 ) { //if ( globalResult != -1 ) // cout << "Result: " << globalResult << endl ; //else //wait some more this_thread::sleep_for( chrono::seconds(1) ) ; } cout << "Result: " << globalResult << endl ; t1.join() ; // main thread waits for the thread t1 to finish /* future future_result = async(launch::async, calculate_value); cout << "Main thread continues to execute...\n"; cout << "Waiting for result...\n"; int result = future_result.get(); // Blocks until the result is available cout << "Result is: " << result << endl; */ return 0; }