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 offuncandargs.Callableand every member ofArgsisMoveConstructible.- Effects:
-
Constructs copies of
funcandargs...in internal storage (denoted byfffandxyz...respectively).If
policyisstd::launch::asyncthen runs INVOKE(fff,xyz...) on its own thread. The returnedstd::futurewill become ready when the task is complete, and will hold either the return value or exception thrown by the function invocation.If
policyisstd::launch::syncthenfffandxyz...are stored in the returnedstd::futureas a deferred function call. Calling thewait()orget()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 toget()on thatstd::future.If
policyisstd::launch::anyor thepolicyargument is omitted then the behaviour is as-if eitherstd::launch::asyncorstd::launch::synchad 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::asynccall returns immediately. - Synchronization:
The completion of the function invocation happens-before a successful return from a call to
wait(),get(),wait_for()orwait_until()on anystd::futureorstd::shared_futureinstance that references the same associated state as thestd::futureobject returned from thestd::asynccall.- Throws:
std::bad_allocif the required internal storage cannot be allocated, otherwisestd::future_errorwhen the effects cannot be achieved, or any exception thrown during the construction offfforxyz....- 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>