std::future
A std::future<T> is a one-shot handle to a value (or exception) that another thread — or a deferred task — will produce. get() waits, returns the T (or void), and leaves the future empty. A second get throws std::future_error.
Detailed Explanation
Producer-consumer needs a place to put one result. promise is the put side. future is the get side. async and packaged_task create the pair for you.
valid() is true if the future refers to a shared state. After get(), or after move, the source is not valid. wait() blocks until the state is ready without consuming it. wait_for / wait_until poll with a timeout and return a future_status (ready, timeout, deferred).
get() on a future<T> moves the T out (or copies if T is not movable in that way). get() on future<void> just waits and rethrows. If the producer called set_exception, get raises that exception in the consumer. That is how async transports errors.
future is move-only. If several waiters need the value, use std::shared_future: auto sf = fut.share();. Each shared_future::get() can run; they see the same stored value. Do not get a future and also share it afterwards.
A future from async joins the worker in its destructor if the task is still running. A future from a promise does not own a thread; destroying it without get just drops the value. The producer that set_values after the future is gone gets a future_error (broken promise) if it is the last reference to the state.
future is not a stream. One value. For a queue of results, use a mutex and a queue, or a library channel.
Do not busy-wait on wait_for(0) in a tight loop without backoff; you will spin a core. Block with get or wait on a condition.
C++ executors and senders (later standards / libraries) generalise futures. std::future remains the standard library's single-value async result.
Code Examples
#include <future>
#include <iostream>
int main() {
std::promise<int> p;
std::future<int> f = p.get_future();
p.set_value(7);
std::cout << f.get() << '\n'; // prints: 7
}#include <future>
#include <thread>
int main() {
std::promise<void> p;
std::future<void> done = p.get_future();
std::thread t([&] { p.set_value(); });
done.wait();
t.join();
}Common Gotchas
Calling `get()` twice
`std::future_error` (`no_state`). Store the value if you need it again, or use `shared_future`.
Destroying an `async` future waits
a local future going out of scope joins. That can surprise you in a return path.
`wait_for` on a deferred future returns `deferred` immediately
the work has not started. `get` will run it.
The future does not extend the life of captured locals in a lambda you passed to `async`
join/`get` before those locals die.