Parallel Standard Library Algorithms
Learn how to add an execution policy to standard library algorithms for parallel execution, and understand the differences in requirements and guarantees.
We'll cover the following...
Overview
As of C++17, the standard library has been extended with parallel versions of most, but not all, algorithms. Changing your algorithms to allow for parallel execution is simply a matter of adding a parameter that tells the algorithm which parallel execution policy to use.
As stressed earlier in this course, if our code base is based upon standard library algorithms, or at least if we have the habit of writing C++ by using algorithms, we will get an instant performance boost almost for free by adding an execution policy where suitable:
auto v = std::vector<std::string>{"woody", "steely", "loopy", "upside_down"};// Parallel sortstd::sort(std::execution::par, v.begin(), v.end());
Once we specify an execution policy, we are in the realm of parallel algorithms, which have some notable differences compared to their original sequential versions. Firstly, the minimum iterator category requirements change from input iterators to forward iterators. Secondly, exceptions thrown by our code (from copy constructors or function objects passed to the algorithm) never reach you. Instead, the algorithm is required to call std::terminate()
. Thirdly, the algorithm’s complexity guarantees (both time and memory) might be relaxed ...