更简洁的线程安全的并行 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. 把线程数量扔给标准库和系统调度。

posted @ 2015-10-24 18:44  wu_overflow  阅读(210)  评论(0编辑  收藏  举报