Use std::async for Concurrency

Learn to use std::async for concurrency.

We'll cover the following

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:

Get hands-on with 1200+ tech skills courses.