~/Parallel For Loops in C++

Jul 10, 2022


Parallel for loops enable efficient use of multi-core CPUs. Modern C++ provides parallelism with OpenMP and std::execution.

OpenMP example
Use #pragma omp parallel for to parallelize a standard for loop.

1
2
3
4
5
6
7
#include <omp.h>
void parallel_loop() {
    #pragma omp parallel for
    for(int i = 0; i < 100; ++i) {
        // work here
    }
}

Compile with -fopenmp.

Standard library parallelism
Since C++17, std::for_each supports parallel execution via std::execution::par.

1
2
3
4
5
6
7
8
9
#include <algorithm>
#include <execution>
#include <vector>
void parallel_for_each() {
    std::vector<int> v(100);
    std::for_each(std::execution::par, v.begin(), v.end(), [](int& n) {
        // work here
    });
}

Your compiler must support C++17 and link with a standard library that implements parallel algorithms.

Choose OpenMP for easy loop parallelism or std::execution for portability. For more detail, see cppreference.

Tags: [cpp] [parallel] [loops]