Execute a task asynchronously
This pattern is licensed under the CC0 Public Domain Dedication.
High-level asynchronous execution of tasks.
On line 14, we call
func as the function to
execute asynchronously. Arguments to
func can be passed as
additional arguments to
std::async. The return value is a
std::future<int>, representing an
value that will be returned from the task at some point in the
std::async will decide whether to execute the task
concurrently or to wait until we request the result and then
execute the task. If we want to specifically request one of these
behaviours, we can use a flag as the first argument. To request
concurrent execution, if possible, we use
std::launch::async. To request that the task
is executed only when the result is needed, we use
On line 18, we use the
get member function to get
the result of the asynchronous task. This blocks until the result
Note: It is important that we capture the future returned by
std::async. If we do not, then the call will always block.