Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::packaged_task — a callable task with a future result

std::packaged_task wraps a callable and stores its result or exception in shared state. std::packaged_task::get_future provides a std::future for retrieving that result; the task itself does not start a new thread.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <future>
std::packaged_task<R(Args...)> task(callable);
std::future<R> result = task.get_future();
task(args...);
result.get();

std::packaged_task<R(Args...)>, declared in <future>, stores a callable with the specified signature. R specifies the result type, and Args... specifies the argument types. The object is movable but not copyable. Constructing a task neither starts the computation nor creates a thread: task(args...) executes the callable in the calling thread.

std::packaged_task::get_future() returns a std::future<R> connected to the same shared state. It does not execute the task and may be called only once for each shared state. Calling it again throws std::future_error with std::future_errc::future_already_retrieved; having no state, for example after default construction or being moved from, produces std::future_errc::no_state.

Invoking the task stores the callable's return value or exception and makes the state ready. result.get() waits for readiness, retrieves the value or rethrows the stored exception; afterward, result.valid() returns false. In the example, the task finishes before get(), so no waiting is needed. Calling get() before running the task in the same thread would block further execution.

Invoking the task again without reset() throws std::future_error with std::future_errc::promise_already_satisfied. reset() creates a new state for another invocation. The task can be invoked again without calling get_future(); a new std::future<R> is needed only to receive the result through a future. Destroying a task whose state is not ready stores std::future_errc::broken_promise in that state, which the consumer can receive through get().

Examples

#include <future>
#include <iostream>

int main() {
    std::packaged_task<int(int, int)> task(
        [](int a, int b) { return a + b; });
    std::future<int> result = task.get_future();

    task(20, 22);
    std::cout << result.get() << '\n';
}

Result

42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources