1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
#include <iostream>
#include <future>
#include <vector>
#include <numeric>
double accum(double* beg, double* end, double init)
// compute the sum of [beg:end) starting with the initial
//value init
{
return std::accumulate(beg, end, init);
}
double comp2(std::vector<double>& v)
{
using Task_type = double(double*, double*, double); // type of task
std::packaged_task<Task_type> pt0{ accum };
// package the task (i.e., accum)
std::packaged_task<Task_type> pt1{ accum };
std::future<double> f0{ pt0.get_future() };
// get hold of pt0's future
std::future<double> f1{ pt1.get_future() };
// get hold of pt1's future
double* first = &v[0];
std::thread t1{ move(pt0),first,first + v.size() / 2,0 };
// start a thread for pt0
std::thread t2{ move(pt1),first + v.size() / 2,first + v.size(),0 };
// start a thread for pt1
// ...
return f0.get() + f1.get();
// get the results
}
int main() {
std::vector v{ 1.2, 2.2, 3.3, 4.4, 5.5, 6.6, 7.6, 8.8 };
std::cout << comp2(v) << '\n';
system("pause");
return 0;
}
|