Skip to content
Tutorials Center
My learning

Topics

Lesson 138 of 171 ยท Concurrency

std::async, Futures and Promises

Learn C++ task-based concurrency - std::async and launch policies, std::future and shared_future, promise, packaged_task, timeouts, and passing exceptions between threads.

With std::thread you start a function, but getting its result back is your problem: you share a variable, protect it with a mutex, and signal completion with a condition variable. Most of the time, though, you don't want a thread at all. You want a task: "compute this in the background, and give me the answer when I ask for it." That's what std::async and std::future provide. You call std::async(f, args...), get a std::future<T> back immediately, and later call .get() to receive the value, waiting if it isn't ready yet. If the task threw an exception, .get() rethrows it in your thread.

This lesson covers std::async and its launch policies, everything you can do with a std::future, the surprising blocking destructor that trips up almost everyone once, std::shared_future for many waiters, and the two lower-level tools that std::async is made of: std::promise and std::packaged_task. It builds on Threads, Mutexes and Locks and Lambda Expressions.

std::async: a task with a result

std::async (in <future>) takes a callable and its arguments, just like std::thread, and returns a std::future of the callable's return type. The future is a one-time "receipt" for the result.

C++ Two sums in parallel with std::async

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

There's no mutex and no shared result variable in sight. The future carries the value from the task to the caller, and the synchronization is built in: everything the task did before returning is visible to you once get() returns.

Arguments are copied into the task, exactly like with std::thread, so a large vector passed directly would be copied once per call. Use std::cref/std::ref (and make sure the referenced object outlives the task), or capture by reference in a lambda: std::async(std::launch::async, [&] { return sum_range(data, 0, half); }).

Launch policies

The first argument of std::async can be a launch policy:

Policy Behavior
std::launch::async Run the task on a new thread, starting now (as if by std::thread).
std::launch::deferred Don't start anything. Run the task lazily, on the thread that first calls get() or wait(). If nobody ever does, it never runs.
std::launch::async | std::launch::deferred Let the implementation choose. This is the default when you omit the policy.

The default sounds convenient, but it makes code unpredictable: the task may run on another thread or synchronously inside get(), so thread_local variables, timing and even deadlock behavior can differ between platforms. Pass std::launch::async explicitly when you want real concurrency.

C++ async versus deferred

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The async task reports another thread; the deferred one reports the main thread, because it ran inside lazy.get(). Deferred tasks are useful for "maybe I'll need this" computations, but they give you no parallelism at all.

Working with a std::future

A std::future<T> has a small interface:

  • get() waits for the result and returns it (or rethrows the stored exception). You can call it only once: it moves the value out, and afterwards the future is empty.
  • valid() tells you whether the future still refers to a result. It's false after get() and for a default-constructed future. Calling get() on an invalid future is undefined behavior (libstdc++ throws std::future_error with "No associated state").
  • wait() waits without taking the result.
  • wait_for(duration) and wait_until(time_point) wait with a timeout and return a std::future_status: ready, timeout or deferred.
  • share() converts it to a std::shared_future (below).

Futures are move-only, like std::unique_ptr: there's exactly one owner of the receipt.

C++ Polling a task with wait_for

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The task sleeps for 250 ms and the loop checks every 100 ms, so you'll normally see two "still working" lines. Thread scheduling can shift that by one in either direction, so code like this must never depend on the exact count. Polling with wait_for(0ms) is also a cheap way to ask "is it done yet?" without blocking at all.

The blocking destructor trap

Here's the rule that surprises people: the destructor of a future returned by std::async waits for the task to finish. (This applies only to futures from std::async; futures from a promise or packaged_task don't block in their destructor.) The rule exists so a task can never outlive the variables it references, but it has a nasty consequence. If you don't store the returned future, it's a temporary, and it's destroyed at the end of the statement, so the "background" call becomes a plain synchronous one.

C++ Fire and forget does not work

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The first pair takes about 400 ms, one job after the other; the second pair takes about 200 ms, because both jobs sleep at the same time. GCC also warns about the first two lines ("ignoring return value ... declared with attribute 'nodiscard'"), because std::async is marked [[nodiscard]]. Take that warning seriously. If you truly want fire-and-forget, std::async is the wrong tool: start a std::jthread that you keep somewhere, or hand the work to a thread pool.

Exceptions cross threads

An exception thrown inside an std::async task doesn't crash the program or vanish. It's caught, stored in the future's shared state, and rethrown when you call get(). That makes error handling with tasks look exactly like ordinary function calls.

C++ get rethrows the task's exception

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The output is in input order, because the loop calls get() in order, even though the four tasks ran concurrently and may have finished in any order. Collecting a std::vector<std::future<T>> and then calling get() on each is the standard "fan out, then gather" pattern.

std::promise: setting a result by hand

std::async couples "run this function" with "deliver its result". A std::promise<T> separates them: it's the writing end of the same shared state that a future reads. Whoever holds the promise calls set_value(v) (or set_exception(e)) exactly once, and the future obtained from promise.get_future() becomes ready. This is useful when the result doesn't come from a single function's return value: a callback, an event, or a value produced halfway through a long-running thread.

C++ A promise fulfilled by a worker thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The three parts show the three ways a promise can end. In the first, main continues as soon as the value is set, while the worker keeps running. In the second, std::current_exception() captures whatever was thrown so it can be rethrown on the other side. In the third, the promise is destroyed with no value, so the future receives a std::future_error with the code broken_promise (with GCC, what() returns std::future_error: Broken promise). That's a safety net: a waiting thread is never left hanging forever because the producer forgot or died.

Calling set_value twice, or get_future twice, throws std::future_error too. For a pure "go" signal without data, use std::promise<void> and set_value() with no argument.

std::packaged_task: a function wrapped with a future

A std::packaged_task<R(Args...)> wraps a callable and connects its return value (or exception) to a future. Calling the task runs the function and fulfills the future. Unlike std::async, it doesn't decide where the function runs: you call it yourself, on whatever thread you like. That's exactly what a thread pool or a job queue needs.

C++ A job queue built on packaged_task

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

This example fills the queue completely before the worker starts, so it needs no mutex. A real job queue is filled while workers run, so it protects the deque with a mutex and a condition variable. Notice that the futures were created before any task ran, and that the exception thrown by the second task traveled through its future just as with std::async. Like futures, packaged tasks are move-only, so the queue stores them by value and moves them out.

std::shared_future: many readers of one result

A std::future's get() can be called once, by one owner. When several threads need the same result, call .share() (or construct a std::shared_future from the future). A shared_future is copyable, every copy can call get() as often as it likes, and get() returns a const T&. Give each thread its own copy; one shared_future object used concurrently from several threads is a data race, but separate copies are safe.

A popular use is a starting gun: many threads wait on one shared_future<void> and all start when a single promise is fulfilled.

C++ A starting gun with shared_future

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The first line always prints 5 waiting and 0 started, because no runner can pass start.wait() before the promise is fulfilled. After set_value() all five run. (C++20 also has std::latch and std::barrier for this kind of coordination, which are better when you don't need to transfer a value.)

Choosing the right tool

You want to... Use
Run a function in the background and get its result std::async(std::launch::async, f, args...)
Run something later, only if needed, on the caller's thread std::async(std::launch::deferred, ...)
Deliver a value from code that isn't a single function return (callbacks, events, mid-thread) std::promise + std::future
Queue work and decide yourself which thread runs it std::packaged_task
Let several threads wait for one result or signal std::shared_future
Long-lived background work that you stop on request std::jthread with a stop token

Limits worth knowing: standard futures have no continuations (no .then(...)), so chaining async steps means blocking on get() or writing your own helper; and std::async(std::launch::async, ...) usually starts a fresh thread per call, so launching thousands of tiny tasks is slow. Production code often uses a thread pool library for that. C++26 adds std::execution ("senders and receivers"), a framework for composing asynchronous work with schedulers; compiler support is only beginning, so treat it as a preview. For CPU-heavy loops over big containers, the parallel algorithms (std::sort(std::execution::par, ...)) are another option.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does auto f = std::async(std::launch::deferred, work); do immediately?

    A deferred task is lazy. It runs synchronously inside the first get() or wait() call, on that caller's thread, and never runs if nobody asks.
  2. 2. Two lines in a row each call std::async(std::launch::async, job); without storing the result. Each job sleeps 200 ms. Roughly how long do the two lines take?

    A future returned by std::async blocks in its destructor until the task finishes. The temporary is destroyed at the end of each statement, so the jobs run one after the other. Store the futures to run them concurrently.
  3. 3. A task started with std::async throws std::runtime_error. What happens?

    The exception is stored in the future's shared state and rethrown by get(), so you handle it with an ordinary try/catch around get().
  4. 4. A std::promise<int> is destroyed without set_value or set_exception ever being called. What does get() on its future do?

    Destroying an unfulfilled promise stores a broken_promise error in the shared state, so waiting threads wake up with an exception instead of hanging forever.
  5. 5. Five threads must all read the same computed result. What should they use?

    std::future::get() works once and the future is move-only. A shared_future is copyable and get() can be called repeatedly; giving each thread its own copy avoids a race on the shared_future object itself.

Summary

  • std::async(f, args...) runs a task and returns a std::future<T>; get() waits for and returns the result, once.
  • Pass std::launch::async for real concurrency. deferred runs lazily on the thread that calls get()/wait(), and the default lets the implementation pick.
  • Use wait_for/wait_until for timeouts and polling; check valid() before get().
  • A future from std::async blocks in its destructor. Discarding it makes the call synchronous, so always store it.
  • Exceptions thrown in a task are rethrown by get(). A destroyed, unfulfilled promise delivers broken_promise.
  • std::promise is the writing end of a future; std::packaged_task wraps a callable with a future so you choose where it runs; std::shared_future lets many threads read one result.

Next: Coroutines, functions that can pause and resume, from lazy generators with co_yield to the machinery behind co_await.