liveBook · Manning

Execution policy

As explained in C++ Concurrency in Action, Second Edition

A C++ standard-library policy that specifies how an algorithm may execute, including whether it may run in parallel.

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

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Explains policy objects, complexity and exception effects, and execution constraints, while leaving thread scheduling to the implementation.
Examples
Demonstrates policy-taking sort and for_each calls, plus synchronized and unsynchronized element updates.
What you can do after
Apply execution policies to standard-library algorithms while accounting for their execution and correctness constraints.
How it connects
Connects parallel algorithms with algorithm complexity, exceptions, iterators, and synchronization.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.