std::promise
A std::promise<T> is the write end of a shared state. You set_value or set_exception once. A std::future<T> from get_future() is the read end. Together they move one result between threads without a mutex you write yourself.
Detailed Explanation
async hides the pair. When you already have a thread (or a callback from a C library), you create a promise, give the future to the waiter, and give the promise to the worker.
get_future() may be called once. A second call throws. Move the future to whoever will get. Move the promise to whoever will set. Both are move-only.
set_value(x) stores x and unblocks waiters. set_value() with no argument is for promise<void>. set_exception(std::current_exception()) or set_exception(std::make_exception_ptr(...)) stores an exception. A second set throws future_error (promise_already_satisfied).
If the promise is destroyed without a set, and a future still exists, the shared state becomes ready with a broken_promise exception. That is how you detect a worker that died without producing a value. Set in a destructor only if you have not already set, and do not throw from that destructor.
set_value_at_thread_exit delays readiness until the setting thread finishes thread-local destructors. Use it when the value refers to thread-locals you need destroyed first. Rare.
The pair does not replace a queue. One shot. For many values, use a queue plus a condition variable, or a library.
You can set_value on the same thread that will get. Then it is just a delayed value, and async(..., deferred) is similar. The interesting case is another thread.
Do not set_value with a pointer to a local of the worker after the worker returns — the waiter will read freed memory. Set a value the waiter will own (string, unique_ptr, an int).
Code Examples
#include <future>
#include <iostream>
#include <thread>
void worker(std::promise<int> p) {
p.set_value(21 * 2);
}
int main() {
std::promise<int> p;
auto f = p.get_future();
std::thread t(worker, std::move(p));
std::cout << f.get() << '\n'; // prints: 42
t.join();
}#include <future>
#include <stdexcept>
#include <thread>
void boom(std::promise<int> p) {
try {
throw std::runtime_error("nope");
} catch (...) {
p.set_exception(std::current_exception());
}
}
int main() {
std::promise<int> p;
auto f = p.get_future();
std::thread t(boom, std::move(p));
try {
f.get();
} catch (const std::runtime_error&) {
t.join();
return 0;
}
t.join();
return 1;
}Common Gotchas
`get_future` twice
throws. Get once, move the future.
`set_value` twice
throws `promise_already_satisfied`.
Destroying a promise without set
the future's `get` throws `broken_promise`. Treat that as a bug in the worker unless it is your shutdown protocol.
`set_value` copies or moves into the shared state
a large object should be moved. The waiter `get`s a move out of the state.