需求:将一个长度为n的vector中的元素累计起来并返回结果:
#include<iostream>
#include<memory>
#include<vector>
#include<thread>
#include<numeric>
#include<math.h>
#include<time.h>
using namespace std;
template<typename Iterator, typename type>
struct accumulate_block {
void operator()(Iterator first, Iterator late, type& result) {
result=std::accumulate(first, late,result);
}
};
template<typename type>
class parallel_accumulate {
int min(int a, int b) {
return a > b ? b : a;
}
public:
type operator()(vector<type>& vect, type init, int min_thread = 10) {
if (!vect.size()) return init;
auto block_begin = vect.begin();
unsigned long const max_thread = std::thread::hardware_concurrency();
unsigned long const num_thread = min(max_thread == 0 ? 2 : max_thread, min_thread);
unsigned long const block_size = vect.size() / num_thread;
vector<std::thread> threads(num_thread - 1);
vector<type> results(num_thread);
accumulate_block<vector<type>::iterator, type> funs;
for (unsigned long i = 0; i < threads.size(); i++) {
auto block_end = block_begin;
std::advance(block_end, block_size);
threads[i] = std::thread(
funs,
block_begin, block_end, std::ref(results[i])
);
block_begin = block_end;
}
results.back() = accumulate(block_begin, vect.end(), 0);
for (int i = 0; i < threads.size(); i++) {
threads[i].join();
}
return std::accumulate(results.begin(), results.end(), init);
}
};
int main() {
time_t S, E;
unsigned int eleNum; cin >> eleNum;
vector<int> vect;
vect.reserve(eleNum);
for (int i = 0; i < eleNum; i++) {
vect.emplace_back(1);
}
cout << "push over" << endl;
S = clock();
cout << std::accumulate(vect.begin(), vect.end(), 0) << endl;
E = clock();
cout << "用时" << (double)(E - S) / 1000 << endl;
S = clock();
cout << parallel_accumulate<int>()(vect, 0) << endl;
E = clock();
cout << "用时" << (double)(E - S) / 1000 << endl;
}