Advertisement
Guest User

Untitled

a guest
Dec 15th, 2019
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. #include <iostream>
  2. #include <future>
  3. #include <vector>
  4. #include <list>
  5. #include <numeric>
  6. #include <iterator>
  7.  
  8. using namespace std;
  9.  
  10.  
  11. template<typename T, typename M1, typename M2>
  12. auto map_reduce(T p, T q, M1 f1, M2 f2,  size_t threads) -> decltype(f1(*p)) {
  13.     vector<future<decltype(f1(*p))> > futures;
  14.     typename T::difference_type len = std::distance(p, q);
  15.     auto doAsyncWork = [len, threads, f1, f2](T p, T q, size_t k) -> decltype(f1(*p)){
  16.         p = next(p, k * (len / threads));
  17.         q = (k < threads - 1) ? next(p, (k + 1) * (len / threads)) : q;
  18.         typename T::difference_type len2 = std::distance(p, q);
  19.         auto res = f1(*p);
  20.         while(++p != q)
  21.             res = f2(res, f1(*p));
  22.         //cout << "k= " << k << " res= " << res << " len= " << len2 << endl;
  23.         return res;
  24.     };
  25.  
  26.     for(size_t i = 0; i < threads; ++i) {
  27.         auto f = std::async(std::launch::deferred, doAsyncWork, p, q, i);
  28.         futures.push_back(std::move(f));
  29.     }
  30.  
  31.     //cout << futures.size() << endl;
  32.     //cout << std::distance(p, q) << endl;
  33.     auto p1 = futures.begin();
  34.     auto p2 = ++p1;
  35.     auto kek1 = p1->get();
  36.     auto kek2 = futures.begin()->get();
  37.     //cout << reinterpret_cast<int*>(p1) << " " << reinterpret_cast<int*>(p2) << endl;
  38.     auto ans = f2(kek1, kek2);
  39.     p2++;
  40.  
  41.     for(; p2 != futures.end(); p2++) {
  42.         auto kek = p2->get();
  43.         ans = f2(ans, kek);
  44.     }
  45.  
  46.     return ans;
  47. }
  48.  
  49. int main()
  50. {
  51.     std::list<int> l = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  52.     // параллельное суммирование в 3 потока
  53.     auto sum = map_reduce(l.begin(), l.end(), [](int i){return i;}, std::plus<int>(), 3);
  54.     cout << sum << endl;
  55.     return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement