Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Concurrency

C++ std::async function

Reference for std::async: run a function asynchronously or lazily, get a std::future, choose std::launch::async or deferred, and avoid the blocking destructor trap.

std::async (header <future>) runs a callable and returns a std::future for its result. It is the shortest route from "compute this" to "compute this on another thread": you pass a function and arguments, keep the future, and call get() when you need the answer. If the function throws, get() rethrows the exception in the calling thread.

The first argument can be a launch policy. std::launch::async starts a new thread of execution immediately. std::launch::deferred runs the function lazily, in the thread that later calls get() or wait(). Without a policy, the implementation may choose either, which makes the call unpredictable. Always name the policy you mean.

C++
auto f = std::async(std::launch::async, [] { return 6 * 7; });
// ... do other work ...
int answer = f.get();       // 42

Try it

C++ Two tasks and their results

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.

C++ deferred, exceptions and 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.

Syntax

C++
template<class F, class... Args>
std::future<std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>>
async(F&& f, Args&&... args);

template<class F, class... Args>
std::future<std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>>
async(std::launch policy, F&& f, Args&&... args);
Name Description
policy std::launch::async, std::launch::deferred, or both OR-ed together (the default).
f Any callable: function, lambda, member function pointer, function object.
args... Arguments, copied or moved into the task. Wrap with std::ref or std::cref to pass by reference.

Returns: a std::future<R> where R is the result type of the call.

Errors / undefined behavior: with launch::async, std::system_error (resource_unavailable_try_again) is thrown if a thread cannot be started. With the default policy the implementation may fall back to deferred instead. A data race between the task and the caller on shared data is undefined behavior.

Usage notes

  • The blocking destructor: a future returned by async with the async policy waits for the task in its destructor. Writing std::async(std::launch::async, f); without keeping the result therefore runs f to completion before the next statement, which is not asynchronous at all. Always store the future.
  • Default policy is a trap. With async | deferred, the work may never start until you call get(); polling with wait_for(0s) can return deferred forever. Specify the policy.
  • Arguments are decayed copies. A const std::vector& parameter still receives a copy unless you pass std::cref(v).
  • Not a thread pool. Each call may create a new thread. For thousands of small tasks, use a pool or algorithms with an execution policy.
  • Exceptions are propagated through get(); they are not lost, but they appear at get(), not where the task was launched.
  • Result is available once per std::future; call .share() for several readers.
  • Output order: if tasks print, their output interleaves unpredictably. Return results and print them from one thread, as the examples do.