#include #include #include #include #include using namespace std ; using namespace chrono_literals; // Enables the use of s, ms, etc. // A function that simulates a long-running task string long_running_task() { // Simulate work this_thread::sleep_for(chrono::seconds(2)); return "Task Completed"; } int main() { cout << "Main thread: Starting asynchronous task..." << endl; // Launch the task asynchronously with a specific policy future future = async(launch::async, long_running_task); cout << "Main thread: Waiting for result with a 1-second timeout check..." << endl; // Check the future's status periodically while (true) { // wait_for returns a status indicating if the result is ready, timed out, or deferred // wait for 1 second future_status status = future.wait_for(1s); if (status == future_status::ready) { cout << "Main thread: Task is ready. Getting result." << endl; // Get the result (this call will not block now) string result = future.get(); cout << "Result: " << result << endl; break; } else if (status == future_status::timeout) { // This happens every 1 second in the loop cout << "Main thread: Timeout reached, but task is still running... checking again." << endl; } // future_status::deferred is also possible if launch::async was not used } cout << "Main thread: Program finished." << endl; return 0; }