std::execution::sequenced_policy
This policy specifies that the algorithm should execute sequentially, i.e., without parallelization. When no execution policy is specified, the algorithms will be executed sequentially.
Syntax of sequenced_policy
stlFunction (std::execution::seq, ...other_arguments...);
We just have to pass the execution policy object names as std::execution::seq as an argument to the supported STL function. The functions are already overloaded to accept it.
Example of sequenced_policy
C++
#include <algorithm> #include <iostream> #include <vector> #include <execution> int main() { std::vector< int > v = { 5, 2, 3, 1, 4 }; std::sort(std::execution::seq, v.begin(), v.end()); for ( auto i : v) std::cout << i << " " ; return 0; } |
Output
5 4 3 2 1
In this example, we create a vector of integers and then sort its elements using the std::sort algorithm with the std::execution::seq policy. The result is a sorted vector with elements { 1, 2, 3, 4, 5 }.
Advantages of sequenced_policy
- Simple and predictable.
- Avoid data races.
- Good for small tasks as parallel overhead does not exist.
Disadvantages of sequenced_policy
- Not efficient for large tasks.
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