Asynchronous Tasks (std::async & std::future)
🔴 Advanced
📖 Definition
The <future> header provides high-level task-based concurrency: std::async runs a function asynchronously and returns a std::future<T> handle. Calling future.get() blocks until the async task completes and returns its result.
💡 Code Example
#include <iostream>
#include <future>
int computeHeavyTask() {
return 42 * 100;
}
int main() {
std::future<int> result = std::async(std::launch::async, computeHeavyTask);
std::cout << "Computing in background...\n";
std::cout << "Result: " << result.get() << "\n"; // Block until result is ready
return 0;
}