just::thread Complete C++ Standard Thread Library by Just Software Solutions

Documentation Home >> Headers >> <future> Header >> std::async function template

std::async is a simple way of running self-contained asynchronous tasks to make use of the available hardware concurrency. A call to std::async returns a std::future that will contain the result of the task. Depending on the launch policy, the task is either run asynchronously on its own thread or synchronously on whichever thread calls the wait() or get() member functions on that future.

enum class launch
{
    any,async,sync
};

template<typename Callable,typename ... Args>
future<result_of<Callable(Args...)>::type>
async(Callable&& func,Args&& ... args);

template<typename Callable,typename ... Args>
future<result_of<Callable(Args...)>::type>
async(launch policy,Callable&& func,Args&& ... args);

Preconditions:

The expression INVOKE(func,args) is valid for the supplied values of func and args. Callable and every member of Args is MoveConstructible.

Effects:

Constructs copies of func and args... in internal storage (denoted by fff and xyz... respectively).

If policy is std::launch::async then runs INVOKE(fff,xyz...) on its own thread. The returned std::future will become ready when the task is complete, and will hold either the return value or exception thrown by the function invocation.

If policy is std::launch::sync then fff and xyz... are stored in the returned std::future as a deferred function call. Calling the wait() or get() member functions on that future will execute INVOKE(fff,xyz...). The value returned or exception thrown by the function invocation will be returned from a call to get() on that std::future.

If policy is std::launch::any or the policy argument is omitted then the behaviour is as-if either std::launch::async or std::launch::sync had been specified. The implementation will choose the behaviour on a call-by-call basis in order to take advantage of the available hardware concurrency without excessive oversubscription.

In all cases, the std::async call returns immediately.

Synchronization:

The completion of the function invocation happens-before a successful return from a call to wait(), get(), wait_for() or wait_until() on any std::future or std::shared_future instance that references the same associated state as the std::future object returned from the std::async call.

Throws:

std::bad_alloc if the required internal storage cannot be allocated, otherwise std::future_error when the effects cannot be achieved, or any exception thrown during the construction of fff or xyz....

Note:

On compilers that don't support variadic templates, an overloaded set of function templates is provided that supports passing of up to 5 arguments.

Header

#include <future>

See Also