Parallel Loops in C++

Exagon picture Exagon · Mar 27, 2016 · Viewed 64.4k times · Source

I wonder if there is a light, straight forward way to compute loops such as for and range based for loops in parallel in C++. How would you implement such a thing? From Scala I know the map, filter and foreach functions maybe it would also possible to perform these parallel? Is there an easy way to achieve this in C++. My primary plattform is Linux but it would be nice if it works cross-plattform.

Answer

Exagon picture Exagon · Aug 19, 2017

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