std::execution::parallel_unsequenced_policy
This policy specifies that the algorithm should execute in parallel and may produce non-deterministic results, i.e., the order in which the elements are processed is not guaranteed. These execution policies are implemented using a combination of hardware and software mechanisms, such as threads and SIMD instructions, to optimize the performance of the algorithms.
Syntax of parallel_unsequenced_policy
stlFunction (std::execution::par_unseq, ...other_arguments...);
This execution policy may include both parallelization and vectorization in contrast to paralled_policy which might only include parallel execution.
Example of parallel_unsequenced_policy
C++
#include <algorithm> #include <iostream> #include <vector> #include <execution> int main() { std::vector< int > v = { 1, 2, 3, 4, 5 }; std::for_each(std::execution::par_unseq, v.begin(), v.end(), []( int x) { std::cout << x << " " ; }); return 0; } |
Output
1 2 3 4 5
In this example, we create a vector of integers and then use the std::for_each algorithm with the std::execution::par_unseq policy to print its elements in parallel and unordered. The result can be any permutation of the input vector, depending on the order in which the elements are processed.
Advantages of parallel_unsequenced_policy
- Faster execution for repetitive operations.
- Can be used on hardware with vector instructions.
Disadvantages of parallel_unsequenced_policy
- Not suitable for all tasks.
- May not be supported on all hardware.
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