Seredenko-V

ForEach_v1

Aug 8th, 2022
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. template <typename ForwardRange, typename Function>
  2. void ForEach(ForwardRange& range, Function function) {
  3.     size_t count_tread = thread::hardware_concurrency();
  4.     size_t number_of_tasks = static_cast<size_t>(ceil(range.size() / count_tread));
  5.     // количество элементов для одного потока
  6.     size_t blocks_for_threads = number_of_tasks == 0 ? number_of_tasks + 1 : number_of_tasks;
  7.     //cout << "blocks_for_threads = " << blocks_for_threads << endl;
  8.  
  9.     vector<ForwardRange::iterator> end_points;
  10.     end_points.reserve(count_tread);
  11.     size_t count = 1;
  12.     for (auto it = range.begin(); it != range.end(); ++it) {
  13.         if (count % blocks_for_threads == 0) {
  14.             end_points.push_back(it);
  15.             //cout << *it << endl;
  16.         }
  17.         ++count;
  18.     }
  19.  
  20.     auto begin_point = range.begin();
  21.     for (auto end_point = end_points.begin(); end_point != end_points.end(); ++end_point) {
  22.         future<void> work_thread = async([begin_point, end_point, &function] {
  23.             for_each(execution::seq, begin_point, *end_point, function);
  24.         });
  25.         //cout << **end_point << endl;
  26.         begin_point = *end_point;
  27.     }
  28.     for_each(execution::par, begin_point, range.end(), function);
  29.  
  30.     //for_each(execution::par, range.begin(), range.end(), function);
  31. }
Advertisement
Add Comment
Please, Sign In to add comment