Petrovi4

ForEachExecutionPolicy

Aug 26th, 2022
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. #include <algorithm>
  2. #include <execution>
  3. #include <future>
  4. #include <iostream>
  5. #include <iterator>
  6. #include <list>
  7. #include <string>
  8. #include <string_view>
  9. #include <type_traits>
  10. #include <vector>
  11.  
  12. using namespace std;
  13.  
  14. template <typename ExecutionPolicy, typename ForwardRange, typename Function>
  15. void ForEach(const ExecutionPolicy& policy, ForwardRange& range, Function function) {
  16.     if constexpr (
  17.         is_same_v<ExecutionPolicy, execution::sequenced_policy>
  18.         || is_same_v<typename iterator_traits<typename ForwardRange::iterator>::iterator_category,
  19.                      random_access_iterator_tag>
  20.         ) {
  21.         for_each(policy, range.begin(), range.end(), function);
  22.  
  23.     } else {
  24.         static constexpr int PART_COUNT = 4;
  25.         const auto part_length = size(range) / PART_COUNT;
  26.         auto part_begin = range.begin();
  27.         auto part_end = next(part_begin, part_length);
  28.  
  29.         vector<future<void>> futures;
  30.         for (int i = 0;
  31.              i < PART_COUNT;
  32.              ++i,
  33.                  part_begin = part_end,
  34.                  part_end = (i == PART_COUNT - 1
  35.                                  ? range.end()
  36.                                  : next(part_begin, part_length))
  37.              ) {
  38.             futures.push_back(async([function, part_begin, part_end] {
  39.                 for_each(part_begin, part_end, function);
  40.             }));
  41.         }
  42.     }
  43. }
  44.  
  45. template <typename ForwardRange, typename Function>
  46. void ForEach(ForwardRange& range, Function function) {
  47.     ForEach(execution::seq, range, function);
  48. }
Add Comment
Please, Sign In to add comment