In C++, how do std::promise and std::packaged_task each connect a result to a std::future, and how does an exception reach the caller?
answer
- provider and return object
- set by hand versus set by the call
- set_exception takes an exception_ptr
- destroyed unsatisfied: broken_promise
basics
~20 sA std::promise is set by hand with set_value or set_exception; a std::packaged_task wraps a callable and stores its return value or exception when called. get() rethrows a stored exception; a provider destroyed unset stores broken_promise.
solid answer
~40 sBoth are **asynchronous providers**: each owns a shared state and hands out one `std::future` through `get_future()`. With `std::promise<T>`, the code that has the result calls `set_value(v)`, or `set_exception(std::current_exception())` inside a `catch (...)`; `set_exception` takes a `std::exception_ptr`. A `std::packaged_task<R(Args...)>` wraps a callable; calling the task runs it and stores either the return value or the thrown exception, so it does the `try`/`catch` for you, and the task can be moved to a thread or a queue. In both cases `get()` rethrows the stored exception in the reader. A provider destroyed before setting anything **abandons** its state, storing `std::future_error` with `future_errc::broken_promise`. Calling `get_future()` twice gives `future_already_retrieved`; setting twice gives `promise_already_satisfied`.
code
cpp · 35 lines#include <future>
#include <iostream>
#include <stdexcept>
#include <thread>
int decode(int image) {
if (image < 0) throw std::invalid_argument("corrupt header");
return image * 10;
}
int main() {
std::promise<int> p; // a hand-written provider
std::future<int> from_promise = p.get_future();
std::thread t([&p] {
try { p.set_value(decode(-1)); }
catch (...) { p.set_exception(std::current_exception()); }
});
std::packaged_task<int(int)> task(decode); // wraps a callable; does the try/catch for you
std::future<int> from_task = task.get_future();
std::thread u(std::move(task), -2);
for (auto* f : {&from_promise, &from_task})
try { std::cout << f->get() << '\n'; }
catch (const std::invalid_argument& e) { std::cout << "rethrown: " << e.what() << '\n'; }
t.join();
u.join();
std::future<int> orphan;
{ std::promise<int> dropped; orphan = dropped.get_future(); } // destroyed unsatisfied
try { (void)orphan.get(); }
catch (const std::future_error& e) {
std::cout << std::boolalpha << (e.code() == std::future_errc::broken_promise) << '\n';
}
}go deeper
Know that std::promise sets a value the matching std::future reads, and that get() rethrows an exception the producer stored.
Explain set_value, set_exception with current_exception, the packaged_task call operator, and broken_promise when a provider is destroyed unset.
Choose promise, packaged_task or async for the shape of the work, wire exceptions through every path, and handle the future_errc conditions.
Prefer a provider that captures exceptions automatically in shared infrastructure, so one forgotten catch block cannot terminate the process.
## The shared state and its two ends The standard library's futures are built on a **shared state** that holds a result — a value or an exception. The side that produces it is an **asynchronous provider**; the side that reads it is an **asynchronous return object** such as `std::future`. `std::async` is one provider, hidden inside a function call. `std::promise` and `std::packaged_task` are the two providers you hold as objects, for when the work does not fit "call this function on another thread". ## `std::promise<T>` — set by hand - `get_future()` returns the one `std::future<T>` for this state; a second call throws `std::future_error` with `future_already_retrieved`. - `set_value(v)` stores a value and makes the state ready. `std::promise<void>` has `set_value()` with no argument, which makes it a one-shot signal. - `set_exception(std::exception_ptr p)` stores an exception. Inside a handler, `std::current_exception()` captures the one being handled; outside, `std::make_exception_ptr(e)` builds one. - Setting a second time, by either function, throws `std::future_error` with `promise_already_satisfied`. - `set_value_at_thread_exit` and `set_exception_at_thread_exit` store the result now but make the state ready only after the thread's `thread_local` objects are destroyed. A promise fits when the result is produced by code you do not control the shape of: a callback from an I/O library, the end of a multi-step state machine, or one thread signalling another exactly once. ## `std::packaged_task<R(Args...)>` — set by the call A `packaged_task` wraps any callable with a matching signature. Its call operator, `task(args...)`, invokes the callable; if the callable returns, the value is stored, and if it throws, the exception is stored — the task never lets it propagate out of `operator()`. Calling the task a second time throws `promise_already_satisfied`; `reset()` gives it a fresh shared state for another run. A task is **move-only**: it can be moved into a `std::thread`, or held in a queue, but not stored directly in a `std::function`, which requires a copyable target. ## How an exception reaches the caller 1. The worker's code throws. 2. The provider stores it: `packaged_task` automatically, a `promise` through `set_exception` in your `catch (...)`. 3. The state becomes ready. 4. The reader calls `get()`, which rethrows the stored exception in the reader's thread, where an ordinary `try`/`catch` handles it. Nothing propagates if no one calls `get()`. And if the worker forgets the `catch` around a promise-based task running in a `std::thread`, the exception leaves the thread function and `std::terminate` is called — the promise never learns about it. ## Abandonment and the error codes | Situation | `std::future_errc` | |---|---| | Provider destroyed, or move-assigned over, without setting a result | `broken_promise`, delivered by the reader's `get()` | | `get_future()` called twice | `future_already_retrieved` | | Result set twice, or task invoked twice | `promise_already_satisfied` | | Operation on an object with no shared state | `no_state` | `broken_promise` is what keeps a reader from waiting forever when a producer dies early: the destructor of the promise or task stores the error and makes the state ready. ## `std::promise<void>` as a one-shot signal A promise does not need to carry data. `std::promise<void>` with `std::future<void>` is a one-shot event: the waiting side calls `get()` or `wait()`, and the signalling side calls `set_value()` with no argument. Unlike a condition variable it has no predicate to forget and cannot lose a wake-up, because the readiness is stored in the shared state; a `wait()` that starts after `set_value()` returns at once. Converting the future to a `std::shared_future<void>` lets many threads wait on the same signal. It also carries failure: a signaller that hits an error can call `set_exception`, and every waiter's `get()` rethrows it. The limit is that it fires exactly once; a repeating signal needs a condition variable or a barrier. ## Choosing among the three providers - **`std::async`**: you have a function and want it run somewhere, now or lazily. - **`std::packaged_task`**: you have a function but want to decide **where and when** it runs — on your own thread, in your own queue. - **`std::promise`**: you do not have a function at all, only a point in some code where the result becomes known.
- Why can't a std::packaged_task be stored in a std::function<void()>?`std::function` requires its target to be copy-constructible, and `packaged_task` is move-only because it owns a unique shared state. Clang rejects the conversion with "call to deleted constructor". Task queues therefore wrap it in a `std::shared_ptr` and store a lambda that calls it, or, from C++23, store it in a `std::move_only_function`.
- What happens if a worker thread using a std::promise throws and never catches?The exception leaves the `std::thread` function, so `std::terminate` is called and the program ends; the promise is never set. The worker must wrap its body in `try { ... } catch (...) { p.set_exception(std::current_exception()); }`. A `std::packaged_task` avoids this because its call operator stores the exception itself.
- set_exception takes the caught std::exception object directly
- A destroyed promise leaves the reader blocked forever
- packaged_task rethrows the callable's exception from its call operator
- You can call get_future() on a promise as many times as you like
- packaged_task starts its own thread when constructed