[futures.async] (original) (raw)

32 Thread support library [thread]

32.9.9 Function template async [futures.async]

The function template async provides a mechanism to launch a function potentially in a new thread and provides the result of the function in a future object with which it shares a shared state.

template<class F, class... Args> [[nodiscard]] future<invoke_result_t<decay_t<F>, decay_t<Args>...>> async(F&& f, Args&&... args);template<class F, class... Args> [[nodiscard]] future<invoke_result_t<decay_t<F>, decay_t<Args>...>> async(launch policy, F&& f, Args&&... args);

Mandates:The following are all true:

Preconditions: decay_­t<F> and each type in decay_­t<Args> meet the Cpp17MoveConstructible requirements.

Effects:The first function behaves the same as a call to the second function with a policy argument oflaunch​::​async | launch​::​deferredand the same arguments for F and Args.

The second function creates a shared state that is associated with the returned future object.

The further behavior of the second function depends on the policy argument as follows (if more than one of these conditions applies, the implementation may choose any of the corresponding policies):

Returns:An object of typefuture<invoke_­result_­t<decay_­t<F>, decay_­t<Args>...>> that refers to the shared state created by this call to async.

[ Note

:

If a future obtained from async is moved outside the local scope, other code that uses the future should be aware that the future's destructor can block for the shared state to become ready.

end note

]

Synchronization:Regardless of the provided policy argument,

If the implementation chooses the launch​::​async policy,

Throws: system_­error if policy == launch​::​async and the implementation is unable to start a new thread, orstd​::​bad_­alloc if memory for the internal data structures could not be allocated.

Error conditions:

[ Example

:

int work1(int value); int work2(int value); int work(int value) { auto handle = std::async([=]{ return work2(value); }); int tmp = work1(value); return tmp + handle.get();
}

[ Note

:

Line #1 might not result in concurrency because the async call uses the default policy, which may uselaunch​::​deferred, in which case the lambda might not be invoked until theget() call; in that case, work1 and work2 are called on the same thread and there is no concurrency.

end note

]

end example

]