#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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?