reduce函数的第二个rhs参数中tbb::parallel_reduce:constness的Lambda形式



我正在尝试使用parallel_reduce:并行构建直方图

#include "stdint.h"
#include "tbb/tbb.h"
#include <algorithm>
#include <vector>
#include <functional>
#include <iostream>
#include <numeric>

void buildhistogram(const uint8_t *inputImage, const size_t numElements, double *outputHist){
auto range = tbb::blocked_range<size_t>(0,numElements);
auto buildHistogramFcn = [&](const tbb::blocked_range<size_t>& r, const std::vector<double>& initHist){
std::vector<double> localHist(initHist);
for (size_t idx = r.begin(); idx != r.end(); ++idx){
localHist[inputImage[idx]]++;
}
return localHist;
};
auto reductionFcn = [&](const std::vector<double>& hist1, const std::vector<double>& hist2){
std::vector<double> histOut(hist1.size());
std::transform(hist1.begin(),hist1.end(),hist2.begin(),histOut.begin(),std::plus<double>());
return histOut;
};
std::vector<double> identity(256);
auto output = tbb::parallel_reduce(range, identity, buildHistogramFcn, reductionFcn);
std::copy(output.begin(),output.end(),outputHist);
}

我的问题涉及到Func在parallel_reduce的lambda形式中的定义。如果您查看英特尔文档:

https://software.intel.com/en-us/node/506154

他们将Func的第二个RHS论点记录为const:

Value Func::operator()(const Range& range, const Value& x)

然而,如果你看一下他们的示例代码,他们定义了一个第二个RHS是非常量的示例,事实上他们修改并返回了这个变量:

auto intelExampleFcn = [](const blocked_range<float*>& r, float init)->float {
for( float* a=r.begin(); a!=r.end(); ++a )
init += *a;
return init;
};

如果我试图将变量"initHist"声明为非常量,并在不分配和返回本地副本的情况下直接使用此内存:

auto buildHistogramFcn = [&](const tbb::blocked_range<size_t>& r, std::vector<double>& initHist){
for (size_t idx = r.begin(); idx != r.end(); ++idx){
initHist[inputImage[idx]]++;
}
return initHist;
}; 

我得到一个编译错误:

/tb/include/tb/parallel_reduce.h:322:24:error:对类型为"const(lambda at buildhistogramTBB.cpp:16:30)"的对象的调用没有匹配的函数my_value=my_real_body(范围,const_cast(my_value))

我感兴趣的是lambda的第二个RHS参数是否真的可以是非常数,因为我希望能够避免将向量从init参数复制到我返回的局部变量。

我是误解了什么,还是英特尔的例子不正确?

英特尔示例中的第二个"非常数"参数是按值传递的。如果要按值传递initHist向量(而不是按引用传递),它也不需要const。(当然,它会复制矢量。但这似乎就是你正在做的。)

最新更新