std::async
Easy asynchronous execution
Interview Relevant: Simple parallelism
std::async
Simple way to run functions asynchronously.
Code Examples
std::async for easy async execution.
cpp
1#include <future>
2
3int compute(int x) {
4 this_thread::sleep_for(chrono::seconds(1));
5 return x * x;
6}
7
8// Async execution
9future<int> f1 = async(compute, 5);
10// Do other work...
11int result = f1.get(); // Wait and get result
12
13// Launch policies
14auto f2 = async(launch::async, compute, 5); // New thread
15auto f3 = async(launch::deferred, compute, 5); // Lazy, runs on get()
16auto f4 = async(launch::async | launch::deferred, compute, 5); // Default
17
18// Parallel computation
19auto sum1 = async(compute, 1);
20auto sum2 = async(compute, 2);
21auto sum3 = async(compute, 3);
22int total = sum1.get() + sum2.get() + sum3.get();
23
24// Exception handling
25future<int> f = async([]() -> int {
26 throw runtime_error("Error!");
27});
28try {
29 int val = f.get(); // Throws here
30} catch (const exception& e) {
31 cout << e.what() << endl;
32}