更简洁的线程安全的并行 accumulate
template<typename Iterator, typename T>
T parallelAccumulate(Iterator first, Iterator last, T init)
{
size_t const length = std::distance(first, last);
if (length == 0){
return init;
}
static constexpr size_t maxChunkSize = 25;
if (length <= maxChunkSize){
return std::accumulate(first, last, init);
}
auto midIterator = first;
std::advance(midIterator, (length / 2));
auto formerHalfResult = std::async(parallelAccumulate<Iterator, T>,
first, midIterator, init);
auto latterHalfResult = parallelAccumulate(midIterator, last, T());
return (formerHalfResult.get() + latterHalfResult);
}
递归地划分数据,短就短在: 1.递归 2. 把线程数量扔给标准库和系统调度。