Parallel Loops in C++
I wonder if there is a light, straight forward way to have loops such as for
and range based-for
loops compute in parallel in C++. How would you implement such a thing? From Scala I know the map
, filter
and foreach
functions and maybe it would also be possible to perform these in parallel? Is there an easy way to achieve this in C++?
My primary platform is Linux, but it would be nice if it worked cross-platform.
With the parallel algorithms in C++17 we can now use:
std::vector<std::string> foo;
std::for_each(
std::execution::par_unseq,
foo.begin(),
foo.end(),
[](auto&& item)
{
//do stuff with item
});
to compute loops in parallel. The first parameter specifies the execution policy
What is your platform? You can look at OpenMP, though it's not a part of C++. But it is widely supported by compilers.
As for range-based for loops, see, e.g., Using OpenMP with C++11 range-based for loops?.
I've also seen few documents at http://www.open-std.org that indicate some efforts to incorporate parallel constructs/algorithms into future C++, but don't know what's their current status.
UPDATE
Just adding some exemplary code:
template <typename RAIter>
void loop_in_parallel(RAIter first, RAIter last) {
const size_t n = std::distance(first, last);
#pragma omp parallel for
for (size_t i = 0; i < n; i++) {
auto& elem = *(first + i);
// do whatever you want with elem
}
}
The number of threads can be set at runtime via the OMP_NUM_THREADS
environment variable.