TBB parallel_reduce - 需要更好地理解"Developer Reference"的例子

TBB parallel_reduce - need better understanding of example from the "Developer Reference"

本文关键字:Developer Reference reduce parallel 更好 TBB      更新时间:2023-10-16

我正在查看页面上的示例,该示例显示了如何以命令式形式调用parallel_reduce。此示例的副本如下:

struct Sum {
  float value;
  Sum() : value(0) {}
  Sum( Sum& s, split ) {value = 0;}
  void operator()( const blocked_range<float*>& r ) {
    float temp = value;
    for( float* a=r.begin(); a!=r.end(); ++a ) {
        temp += *a;
    }
    value = temp;
  }
  void join( Sum& rhs ) {value += rhs.value;}
};
float ParallelSum( float array[], size_t n ) {
  Sum total;
  parallel_reduce( blocked_range<float*>( array, array+n ),
                 total );
  return total.value;
}

我的问题是 - 为什么我们需要operator()体中的变量float temp?如果求和直接与value数据成员一起使用,则会发生什么情况:

for( float* a=r.begin(); a!=r.end(); ++a ) value += *a;

直接应用时它将起作用,因为类的每个实例同时由一个线程使用。

但是直接使用此变量可能会阻止编译器对循环进行矢量化。我会通过缓存 r.end() 来进一步处理这个逻辑,因为如果它没有正确内联,它也会破坏矢量化。虽然,它与TBB本身没有直接关系,只是一般的C++优化技巧。

相关文章: