skip to content

In C++, how does std::future::get deliver a std::async task's result or exception, and why can it be called only once?

level: juniorimportance: should knowfreq 58%

answer

  1. the shared state holds value or exception
  2. get blocks, then moves the value out
  3. valid() is false afterwards
  4. shared_future for many readers

basics

~20 s

std::future::get waits until the shared state is ready, then moves the stored value out or rethrows the stored exception. It releases the state, so valid() becomes false and a second get() is undefined; std::shared_future allows repeated get().

solid answer

~40 s

`std::async` creates a **shared state** that will hold either the function's return value or the exception it threw, and returns a `std::future` that refers to it. `get()` waits until the state is ready, then either returns the value — `future<T>::get` returns it as `std::move(v)` — or rethrows the stored exception in the calling thread. Either way it **releases** the shared state, and the standard's postcondition is `valid() == false`. Calling `get()` again is undefined behaviour; the standard recommends that implementations throw `std::future_error` with `future_errc::no_state`, which libstdc++ does, while libc++ does not check. When several threads need the same result, call `share()` to get a copyable `std::shared_future`, whose `get()` returns a `const T&` and can be called any number of times.

code

cpp · 21 lines
cpp
#include <future>
#include <iostream>
#include <stdexcept>

int main() {
    std::future<int> f = std::async(std::launch::async, [] { return 7; });
    std::cout << f.get() << ' ' << std::boolalpha << f.valid() << '\n';
    // (void)f.get();   // undefined behaviour: f no longer has a shared state

    std::future<int> bad = std::async(std::launch::async, []() -> int {
        throw std::runtime_error("decode failed");
    });
    try {
        (void)bad.get();             // the worker's exception is rethrown here
    } catch (const std::runtime_error& e) {
        std::cout << "caught: " << e.what() << '\n';
    }

    std::shared_future<int> s = std::async(std::launch::async, [] { return 8; }).share();
    std::cout << s.get() << ' ' << s.get() << ' ' << s.valid() << '\n';
}

go deeper

for a junior

Know that std::async returns a std::future, that get() waits and returns the value or rethrows the exception, and that get() is called once.

for a middle

Explain the shared state, the move-out return, valid() turning false, and when to switch to shared_future and copy it per thread.

for a senior

Know that a second get() is undefined and libraries differ, and design code so each future has exactly one reader or a shared_future copy per reader.

for a principal

Make sure every asynchronous result has an owner who calls get(), or failures in background work vanish without a trace.

## The shared state Every future in the standard library talks to a **shared state**: a small object that holds some status and a result that is either a value or an exception. Something produces the result — `std::async`, a `std::promise`, a `std::packaged_task` — and a `std::future<T>` (or `std::shared_future<T>`) reads it. The future is the **asynchronous return object**; the producer is the **asynchronous provider**. When the producer stores its result, it "makes the shared state ready" and wakes anyone waiting. For `std::async`, the stored result is whatever the function returned, and if the function threw, the exception is stored instead. Nothing escapes the worker thread, so the program is not terminated — unlike an exception leaving the top of a plain `std::thread`'s function, which calls `std::terminate`. ## What `get()` does, step by step 1. It **waits** until the shared state is ready (for a deferred `std::async` task, it runs the function in the calling thread at this point). 2. If the result is an exception, it **rethrows** that exception in the caller. 3. Otherwise `future<T>::get()` returns the stored value as `std::move(v)`; `future<T&>::get()` returns the stored reference; `future<void>::get()` returns nothing. 4. It **releases** the shared state. The postcondition is `valid() == false`. Because the value is moved out, a second `get()` would have nothing to return, which is why the type is single-use by design. `get()` is also the only point where a `std::async` task's exception becomes visible: if no one calls `get()`, the exception is destroyed with the shared state. ## Calling `get()` twice The standard says that calling any member other than the destructor, move assignment, `share` or `valid` on a future with `valid() == false` is **undefined**. It adds a recommendation that implementations detect it and throw `std::future_error` with `future_errc::no_state`. Implementations differ: | Library | Second `get()` on a `std::future` | |---|---| | libstdc++ (GCC 16 headers) | checks the state and throws `std::future_error` (`no_state`) | | libc++ (LLVM 23 headers) | does not check; it uses the null state pointer, and a test run crashed | Neither is something to rely on. Check `valid()` if the code path is unclear, or restructure so each future is read once. ## `std::future` versus `std::shared_future` | | `std::future<T>` | `std::shared_future<T>` | |---|---|---| | Copyable | no, move-only | yes | | `get()` calls | one | any number, from any copy | | `get()` returns | `T` (moved out) | `const T&` | | Created by | `std::async`, `get_future()` | `future.share()` or construction from a `future&&` | `share()` moves the state into a new `shared_future` and leaves the original future with `valid() == false`. Give each thread **its own copy** of the `shared_future` rather than a reference to one object: the standard notes that `shared_future` member functions "do not synchronize with themselves, but they synchronize with the shared state", and that concurrent access through references returned by `get()` must be read-only or otherwise synchronized. ## Waiting without consuming `get()` is the only member that consumes the result. The others leave it in place: - `valid()` reports whether the future still refers to a shared state; it is the one safe question to ask a future that may already have been read. - `wait()` blocks until the state is ready and returns nothing; the value is still there for a later `get()`. - `wait_for(duration)` and `wait_until(time_point)` block at most that long and return a `std::future_status`: `ready`, `timeout`, or `deferred` for a lazy `std::async` task that has not started. So a caller that wants to time out can poll with `wait_for` and call `get()` once it reports `ready`, and the single-use rule is never in the way. Keep in mind that `get()` itself has no timeout; a task that never finishes blocks its reader indefinitely. ## Things candidates get wrong - Expecting a default value or an error code from `get()` when the task threw; the exception itself is rethrown. - Calling `get()` in a loop to "check" a result, instead of `wait_for` or `valid()`. - Passing one `std::future` to several threads; it is move-only, and only one of them can `get()`. - Sharing a single `shared_future` object by reference across threads instead of copying it. - Forgetting that a future obtained from `std::async` is the only channel for the task's exception; dropping it silently drops the error.

  • What happens to an exception thrown by a std::async task if nobody ever calls get()?
    It stays in the shared state and is destroyed with it; nothing is reported and the program is not terminated. That differs from a `std::thread`, where an exception escaping the thread function calls `std::terminate`. Dropping the future of a task that can fail therefore drops its error silently.
  • How do several threads wait for the same result?
    Call `share()` on the `std::future` (or construct a `std::shared_future` from it) and give each thread its own copy. Every copy can call `wait()` and `get()` any number of times; `get()` returns a `const T&` to the single stored value, so readers must not modify it without their own synchronization.

  • get() returns a default value when the task threw
  • You can call get() repeatedly to read the cached result
  • An exception in a std::async task terminates the program like one in std::thread
  • std::future is copyable, so each thread can hold one
  • Calling get() twice always throws std::future_error