【问题标题】:tbb::parallel_reduce on std::vectorstd::vector 上的 tbb::parallel_reduce
【发布时间】:2014-08-15 10:26:47
【问题描述】:

下面是一个简单的并行程序,使用 tbb 计算标准向量中元素的总和。
有人可以帮我理解为什么它输出错误的结果吗?

#include  <iostream>
#include <algorithm>
#include <numeric>

#include <tbb/tbb.h>

struct Sum {
    int value;

    Sum() : value(0) {}
    Sum(Sum&s, tbb::split) : value(0) {}

    void operator()(const tbb::blocked_range<std::vector<int>::iterator>& r) {

        value = std::accumulate(r.begin(), r.end(), 0);
    }

    void join(Sum& rhs) { value += rhs.value; }
};


int main()
{   
    std::vector<int> a(100);
    std::fill(a.begin(), a.end(), 1);

    Sum sum;
    tbb::parallel_reduce(tbb::blocked_range<std::vector<int>::iterator>(a.begin(), a.end()), sum);

    std::cout << sum.value << std::endl;

    return 0;  
}

【问题讨论】:

    标签: c++ c++11 concurrency tbb


    【解决方案1】:

    既然你用错了accumulate。应该是

    value = std::accumulate(r.begin(), r.end(), value);
    

    【讨论】:

    • 通常是value += ..它只是std::accumulate(),它提供了另一种写value = sum + value的方式。
    【解决方案2】:

    为什么不用tbb_parallel_reduce 的函数形式呢?它避免了对您的struct Sum 的需要,并且看起来更直观,例如(未测试)

    typedef tbb::blocked_range<std::vector<int>::iterator> range_type;
    auto sum=tbb_parallel_reduce(range_type(a.begin(),a.end()), 0,
                                 [](range_type const&r, int init)
                                 { return std::accumulate(r.begin(),r.end(),init); },
                                 std::plus<int>());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 2012-03-07
      相关资源
      最近更新 更多