Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <future>
- #include <vector>
- #include <list>
- #include <numeric>
- #include <iterator>
- using namespace std;
- template<typename T, typename M1, typename M2>
- auto map_reduce(T p, T q, M1 f1, M2 f2, size_t threads) -> decltype(f1(*p)) {
- vector<future<decltype(f1(*p))> > futures;
- typename T::difference_type len = std::distance(p, q);
- auto doAsyncWork = [len, threads, f1, f2](T p, T q, size_t k) -> decltype(f1(*p)){
- p = next(p, k * (len / threads));
- q = (k < threads - 1) ? next(p, (k + 1) * (len / threads)) : q;
- typename T::difference_type len2 = std::distance(p, q);
- auto res = f1(*p);
- while(++p != q)
- res = f2(res, f1(*p));
- //cout << "k= " << k << " res= " << res << " len= " << len2 << endl;
- return res;
- };
- for(size_t i = 0; i < threads; ++i) {
- auto f = std::async(std::launch::deferred, doAsyncWork, p, q, i);
- futures.push_back(std::move(f));
- }
- //cout << futures.size() << endl;
- //cout << std::distance(p, q) << endl;
- auto p1 = futures.begin();
- auto p2 = ++p1;
- auto kek1 = p1->get();
- auto kek2 = futures.begin()->get();
- //cout << reinterpret_cast<int*>(p1) << " " << reinterpret_cast<int*>(p2) << endl;
- auto ans = f2(kek1, kek2);
- p2++;
- for(; p2 != futures.end(); p2++) {
- auto kek = p2->get();
- ans = f2(ans, kek);
- }
- return ans;
- }
- int main()
- {
- std::list<int> l = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
- // параллельное суммирование в 3 потока
- auto sum = map_reduce(l.begin(), l.end(), [](int i){return i;}, std::plus<int>(), 3);
- cout << sum << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement