Skip to content

The simplest way for asynchronous execution – std::async

Principle

std::async executes some piece of code in the background, possibly within a separate thread. Access to results (and waiting for thread execution) is possible via std::future.

Example

Asssume you have one or more time consuming calculations finally providing some result:

SomeResult CalculateSomething(int in_val)
{
    return ...
}

Then you can simply execute them asynchronously and in parallel by calling them via std::async. The result can be accesssed by use of a future.

#include<future>
{
    // Start 2 calculations in parallel
    std::future<SomeResult> calc1 = std::async(&CalculateSomething,17);
    std::future<SomeResult> calc2 = std::async(&CalculateSomething,42);
    // Do something else
    ...
    // Wait for the results
    SomeResult result1 = calc1.get();
    SomeResult result2 = calc2.get();
}

Remarks

  • std::async decides on its own if really a separate thread is started. The decision may depend on the number of available processors and the number of already existing threads.
  • instead of a function you can also use a function object or a lambda expression:
    SomeVal x;
    std::future calc3 = std::async([=]{return x*x*x;});
  • Attention: Unwanted sequential execution.
    Do not forget to use the future instance to request the result. Otherwise the call of std::async will return a temporary future object which is immediatelly destroyed. Within destructor the future will wait for the termination of the asynchronous calculation. As a consequence the following actions are executed one after the other:
    // Sequential execution!
    std::async (&CalculateSomething,17);
    std::async (&CalculateSomething,42);

For a more detailed discussion of problems with async and destructors of future and thread see Herb Sutter: async, ~future, and ~thread

std::async – most used features

You can provide an explicit start policy as first constructor argument for std::async:

Start policyDescription
std::launch::asyncstart separate execution thread
std::launch::deferredstart calculation in the same thread at the moment when result is requested via the future (lazy evaluation)

For more info see std::async – complete reference at CppReference.com