std::async & Futures
std::async (<future>)
std::future<double> f = std::async(std::launch::async, compute_report, month);
// ... do other work ...
double result = f.get(); // waits if necessary, then returns the value
std::launch::async— run on a new thread ✅ (be explicit)std::launch::deferred— run lazily on the calling thread whenget()is called- Default (both) lets the implementation choose — surprising, so specify it
std::future<T>
get()— wait and retrieve the result (only once; afterwards the future is invalid)wait(),wait_for(timeout)— wait without retrieving;wait_forreturnsreadyortimeoutvalid()— still has a shared state?
Exceptions travel through futures ✅
If the task throws, the exception is stored and re-thrown by get() in the calling thread.
std::promise<T> — set a value manually
A promise is the "write end", its future the "read end":
std::promise<int> p;
std::future<int> f = p.get_future();
std::thread t([&p] { p.set_value(42); });
f.get(); // 42
std::shared_future
Several threads can wait for and read the same result.
⚠️ The blocking destructor gotcha
A future returned by std::async blocks in its destructor until the task finishes. Calling std::async(...) without keeping the future runs the task synchronously!
When to use what
| Need | Tool |
|---|---|
| Run a function, get its result | std::async + future |
| Long-running worker with cancellation | std::jthread + stop_token |
| Many small tasks | a thread pool (or a library) |
| Shared state updates | mutex / atomic |
Example
#include <chrono>
#include <future>
#include <iostream>
#include <numeric>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>
double monthly_total(int month) {
std::this_thread::sleep_for(std::chrono::milliseconds(30)); // pretend this is slow
std::vector<double> fake(30, month * 100.0);
return std::accumulate(fake.begin(), fake.end(), 0.0);
}
double risky_sync(bool fail) {
if (fail) throw std::runtime_error("server unreachable");
return 1.0;
}
int main() {
auto start = std::chrono::steady_clock::now();
std::vector<std::future<double>> futures;
for (int m = 1; m <= 4; ++m)
futures.push_back(std::async(std::launch::async, monthly_total, m)); // all start now
double year = 0;
for (int m = 1; m <= 4; ++m) {
double t = futures[m - 1].get(); // waits if needed
std::cout << "month " << m << ": " << t << '\n';
year += t;
}
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
std::cout << "total: " << year << ", ran in parallel? " << (ms < 110 ? "yes" : "maybe not") << '\n';
auto failing = std::async(std::launch::async, risky_sync, true);
try {
failing.get(); // exception re-thrown here
} catch (const std::exception& e) {
std::cout << "task failed: " << e.what() << '\n';
}
std::promise<std::string> promise;
std::future<std::string> result = promise.get_future();
std::thread producer([&promise] {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
promise.set_value("sync complete");
});
if (result.wait_for(std::chrono::seconds(2)) == std::future_status::ready)
std::cout << "promise delivered: " << result.get() << '\n';
producer.join();
auto lazy = std::async(std::launch::deferred, [] { return 7 * 6; }); // runs on get()
std::cout << "deferred result: " << lazy.get() << ", future still valid? " << std::boolalpha << lazy.valid() << '\n';
return 0;
}
/* Output:
month 1: 3000
month 2: 6000
month 3: 9000
month 4: 12000
total: 30000, ran in parallel? yes
task failed: server unreachable
promise delivered: sync complete
deferred result: 42, future still valid? false
*/