How do I use futures and promises?

C++, futures, promises, asynchronous programming, multithreading
Explore how to use futures and promises in C++ for effective asynchronous programming and managing multithreading tasks.
#include <iostream>
#include <future>
#include <thread>

// A simple function to demonstrate futures and promises
int findAnswer() {
    std::this_thread::sleep_for(std::chrono::seconds(2)); // Simulate a long task
    return 42; // The answer to life, the universe, and everything
}

int main() {
    // Create a promise object
    std::promise promise;

    // Get the future from the promise
    std::future future = promise.get_future();

    // Launch a thread that will set the value of the promise
    std::thread t([&promise]() {
        // Compute the answer and set it in the promise
        promise.set_value(findAnswer());
    });

    std::cout << "Waiting for the answer..." << std::endl;

    // Get the result using future
    std::cout << "The answer is: " << future.get() << std::endl;

    // Wait for the thread to finish
    t.join();

    return 0;
}
    

C++ futures promises asynchronous programming multithreading