Use std::async for concurrency
std::async()
runs a target function asynchronously and returns a std::future
object to carry the target function's return value. In this way, async()
operates much like std::thread
but allows return values.
Let's consider the use of std::async()
with a few examples.
How to do it…
In its simplest forms, the std::async()
function performs much the same task as std::thread
, without the need to call join()
or detach()
and while also allowing return values via a std::future
object.
In this recipe, we'll use a function that counts the number of primes in a range. We'll use chrono::steady_clock
to time the execution of each thread.
- We'll start with a couple of convenience aliases:
using launch = std::launch; using secs = std::chrono::duration<double>;
std::launch
has launch policy constants, for use with the async()
call. The secs
alias is a duration
class, for timing our prime number calculations...