std::execution::parallel_policy
This policy specifies that the algorithm should execute in parallel, i.e., using multiple threads. The standard does not specify the number of threads that should be used, but it should be more than one.
Syntax of parallel_policy
stlFunction (std::execution::par, ...other_arguments...);
The execution policy object std::execution::par is passed as the argument to the STL algorithm function.
Example of parallel_policy
C++
#include <algorithm> #include <execution> #include <iostream> #include <vector> int main() { std::vector< int > v1 = { 1, 2, 3, 4, 5 }; std::vector< int > v2(5); std::transform(std::execution::par, v1.begin(), v1.end(), v2.begin(), []( int x) { return x * x; }); for ( int i : v2) { std::cout << i << " " ; } return 0; } |
Output
1 4 9 16 25
In this example, we create two vectors of integers v1 and v2, and then use the std::transform algorithm with the std::execution::par policy to square the elements of v1 and store the result in v2. The result is a vector v2 with elements { 1, 4, 9, 16, 25 }.
Advantages of parallel_policy
- Faster execution for larger tasks.
- Optimal usage of multi-core systems.
Disadvantages of parallel_policy
- May introduce overhead.
- May not always be faster than sequential execution due to this overhead.
- Can introduce race conditions.
Execution Policy of STL Algorithms in Modern C++
C++ algorithms are a set of pre-defined functions that can perform various operations on containers, such as arrays, vectors, and lists. These algorithms have a defined execution policy that determines how they execute and how they interact with the underlying hardware.
The C++ 17 standard introduces three new execution policies and one policy was introduced in C++20. These execution policies in C++ allow algorithms to be executed in different ways depending on the requirements of the task and the hardware available. They are as follows:
- std::execution::sequenced_policy
- std::execution::parallel_policy
- std::execution::parallel_unsequenced_policy
- std::execution::unsequenced_policy
Contact Us