An execution policy tells a C++ standard-library algorithm how it may execute. C++17 added policy-taking overloads to many algorithms; pass the policy as the first argument. For example, std::execution::par permits parallel execution but does not require it. section 10.1
The standard provides three policy objects, declared in <execution>:
- std::execution::seq requires operations to run on the calling thread, in a definite but unspecified order. section 10.2.2
- std::execution::par permits parallel execution. Choose it when the algorithm’s work can safely run in parallel. section 10.3.1
- std::execution::par_unseq permits parallel execution with additional scope for reordering and interleaving, but disallows synchronization within the operations. section 10.3.1
Supplying any standard policy can relax an algorithm’s complexity requirements. Uncaught exceptions from its operations call std::terminate; std::bad_alloc may still be thrown. With par_unseq, mutexes and atomic variables cannot be used in the operations. With seq, execution stays on one thread, but do not rely on the operation order matching the overload without a policy. section 10.2.1 section 10.3.1 section 10.2.2
std::vector<int> my_data;
std::sort(std::execution::par,my_data.begin(),my_data.end());
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":1,\"ch\":10},{\"line\":1,\"ch\":29}]]"}
!@%STYLE%@!
This sort call passes par before the iterator range, permitting the library to use parallel execution. section 10.1
std::for_each(std::execution::par,v.begin(),v.end(),do_stuff);
This applies do_stuff to each element using par; how elements are divided among threads is an implementation detail. section 10.3.1
