How to do it...

To implement a parallel version of the map function, do the following:

  1. Define a function template that takes the begin and end iterators to a range and a function to apply to all the elements:
        template <typename Iter, typename F>        void parallel_map(Iter begin, Iter end, F f)        {        }
  1. Check the size of the range. If the number of elements is smaller than a predefined threshold (for this implementation, the threshold is 10,000), execute the mapping in a sequential manner:
        auto size = std::distance(begin, end);        if(size <= 10000)          std::transform(begin, end, begin, std::forward<F>(f));
  1. For larger ranges, split the work on multiple threads and let each thread map a part of the range. These parts should not overlap to avoid the ...

Get Modern C++ Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.