下面是一个简单的并行程序,用于计算使用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;
}
答案 0 :(得分:3)
由于您使用accumulate
错误。它应该是
value = std::accumulate(r.begin(), r.end(), value);
答案 1 :(得分:1)
为什么不使用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>());