Futures and Promises in C++
Frequently Asked Questions
QWhat is the difference between std::async and creating a std::thread?
QWhat is std::packaged_task and when would I use it?
QWhat does std::launch::deferred do exactly?
QWhat is the fire-and-forget anti-pattern with std::async?
#include <iostream>
#include <format>
#include <future>
#include <thread>
#include <chrono>
#include <numeric>
#include <vector>
#include <stdexcept>
using namespace std::chrono_literals;Watch out: std::async with launch::async returns a future whose destructor blocks until the task completes. Discarding the future (e.g., not capturing the return value) makes the call synchronous. -----------------------------------------------
long long compute_sum(int from, int to) {
long long sum = 0;
for (int i = from; i <= to; ++i) sum += i;
return sum;
}2 std::promise / std::future -- manual producer/consumer
std::promise / std::future -- manual producer/consumer.
Use this when it cleanly solves the problem in front of you.
it after set_exception(), throws std::future_error.
Use it in code like: void producer(std::promise<std::string> promise) {.
it after set_exception(), throws std::future_error. Each promise can deliver exactly one result.
Watch out: calling promise::set_value() more than once, or calling
void producer(std::promise<std::string> promise) {
std::this_thread::sleep_for(100ms); // Simulate work
promise.set_value("Hello from the producer thread!");
}3 Exception propagation through futures
If the async task throws, the exception is stored in the future and re-thrown on .get().
If the async task throws, the exception is stored in the future and re-thrown on .get().
If the async task throws, the exception is stored in the future and re-thrown on .get().
Use it in code like: int risky_computation(int x) {.
If the async task throws, the exception is stored in the future and re-thrown on .get().
int risky_computation(int x) {
if (x < 0) {
throw std::invalid_argument("Negative input not allowed");
}
return x * x;
}