Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

std::async

Use case

Run analysis tasks in parallel and collect the results.

Explanation

std::async runs a function asynchronously and returns a std::future. We can call .get() to wait for and retrieve the result. (Use std::launch::async to force a new thread and std::launch::deferred for lazy evaluation.)

Code

#include <future>
#include <iostream>

int analyze(const char *segment) {
  std::cout << "Analyzing " << segment << "\n";
  return 100;
}

int main() {
  auto f1 = std::async(std::launch::async, analyze, "__TEXT");
  auto f2 = std::async(std::launch::async, analyze, "__DATA");

  int r1 = f1.get();
  int r2 = f2.get();

  std::cout << "Results: " << r1 << ", " << r2 << "\n";

  return 0;
}

View on GitHub.

Output

$ ./src/c++11/build/std-async
Analyzing __TEXT
Analyzing __DATA
Results: 100, 100