C++ 17 – Parallelism and Concurrency for STL Algorithms

C++ STLs provide containers such as an arrayset, and map. Each of the containers will come with predefined algorithms which you can execute on these containers without having to write code by yourself.

For example, a vector is a container, and std::sort is an algorithm that can sort the elements in the vector without having to write code ourselves. Below v is a vector, and std::sort would sort the vector elements.

std::sort(v.begin(), v.end());

C++ 17 introduced a new feature to parallelize such STL algorithms. For example, if the above statement needs to get parallelized, i.e., if it should get executed by multiple threads to do the job faster, all you need to do is pass an execution policy as below as the first argument into the STL algorithm.

std::sort(std::execution::par, v.begin(), v.end());

That’s it. The sort algorithm converts into a multi-threaded or parallel code.

Execution policies supported by C++ 17 STL algorithms

We spoke about std::execution::par, but there are three execution policies supported for STL algorithms from C++ 17 onwards.

  1. std::execution::seq: The execution policy “seq” is the default till C++ 17. It would enforce the sequential execution of the algorithm.
  2. std::execution::par: The execution policy “par” will enable parallel execution. The algorithm is divided and run by multiple threads.
  3.  std::execution::par_unseq: The execution policy “par_unseq” will enable a mix of parallel and vectorized execution of the algorithm.

List of major STL algorithms that support parallel execution policy

The STL algorithms that support parallel execution policy are std::for_each, std::count, std::count_if, std::find, std::find_if, std::find_if_not, std::reduce, std::transform_reduce, std::accumulate, std::inner_product, std::partial_sum, std::iota, std::sort and std::merge.

Sample C++ program for parallel execution policy

Below is a simple program that applies parallel execution policy on the std::sort STL algorithm. We print the vector elements before and after the std::sort to check it is sorted. The complete program is available for download at https://github.com/codeversionmaster/cplusplus/blob/cplusplus17/stl_parallel.cpp.

$ cat stl_parallel.cpp
#include <iostream>
#include <algorithm>
#include <execution>
#include <vector>

int main() {
  std::vector<int> v = {2, 1, 5, 3, 4};

  for(auto it:v) { std::cout << it << " "; }
  std::cout << std::endl;

  // Use the parallel execution policy to sort the vector
  std::sort(std::execution::par, v.begin(), v.end());

  for(auto it:v) { std::cout << it << " "; }
  std::cout << std::endl;

  return 0;
}

You can compile and run as below to see the output.

$ g++ -std=c++17 stl_parallel.cpp -o stl_parallel
~/cplusplus$ ./stl_parallel 
2 1 5 3 4 
1 2 3 4 5