To implement a parallel version of the map function, do the following:
- 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) { }
- 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));
- 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 ...