Parallel Algorithms (Execution Policies) in C++
Since C++17, most algorithms accept an execution policy as the first argument: std::sort(std::execution::par, ...) parallelizes across threads with one token added. seq forces sequential, par permits threading, par_unseq additionally allows vectorization β same algorithm, same result (for associative, commutative-safe operations), dramatically less wall time on big data.
Parallelism demands discipline: element operations must be thread-safe and order-independent (no shared mutable state, no I/O inside), and small ranges run slower parallel from thread overhead. Measure β par wins on millions of elements, loses on hundreds.
One token parallelizes
Add std::execution::par (and <execution>) as the first argument β sort, transform, for_each all scale with cores.
par vs par_unseq
par threads the work; par_unseq also vectorizes (SIMD) β fastest, but forbids even mutexes inside element code.
Operations must be safe
No data races, no shared mutation, no ordering assumptions β pure per-element work parallelizes; entangled work corrupts.
Size matters
Thread startup costs dominate small ranges β parallelize bulk data (millions), keep small loops sequential.
#include <iostream>#include <vector>#include <algorithm>#include <execution>Β int main() { std::vector<int> v{3, 1, 2}; std::sort(std::execution::par, v.begin(), v.end()); std::cout << v[0] << v[1] << v[2] << std::endl; return 0;}Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself β building beats watching.