扩展代码,
#include <future>
#include <iostream>
#include <numeric>
#include <thread>
#include <vector>
using namespace std;
double accum(double* beg, double* end, double init) { return accumulate(beg, end, init); }
double comp2(vector<double>& v) {
using Task_type = double(double*, double*, double); // type of task
packaged_task<Task_type> pt0{accum}; // package the task (i.e., accum)
packaged_task<Task_type> pt1{accum};
future<double> f0{pt0.get_future()}; // get hold of pt0's future
future<double> f1{pt1.get_future()}; // get hold of pt1's future
double* first = &v[0];
thread t1{move(pt0), first, first + v.size() / 2, 0}; // start a thread for pt0
thread t2{move(pt1), first + v.size() / 2, first + v.size(), 0}; // start a thread for pt1
// ...
t1.join(); // wait for the thread to complete
t2.join(); // wait for the thread to complete
return f0.get() + f1.get(); // get the results
}
int main() {
vector<double> v{1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5};
double result = comp2(v);
cout << "Result: " << result << endl;
return 0;
}