C++ parallel_for error

C++ parallel_for error

本文关键字:error for parallel C++      更新时间:2023-10-16

我正在尝试学习如何使用TBB,所以我正在修改我发现的一个示例程序,该程序旨在计算复数数组的幂。最初,它将一个数组传递到parallel_fo循环中,但我正在尝试更改它,使其以向量形式传递。但是,我无法编译我的代码;我得到以下错误(使用g++-gprogram_name.cpp-ltbb编译):

error: passing ‘const std::complex<double>’ as ‘this’ argument
       discards qualifiers [-fpermissive] result[i] = z;

我的代码如下:

#include <cstdlib>
#include <cmath>
#include <complex>
#include <ctime>
#include <iostream>
#include <iomanip>
#include "tbb/tbb.h"
#include "tbb/blocked_range.h"
#include "tbb/parallel_for.h"
#include "tbb/parallel_for_each.h"
#include "tbb/task_scheduler_init.h"
using namespace std;
using namespace tbb;
typedef complex<double> dcmplx;
dcmplx random_dcmplx ( void )
{
   double e = 2*M_PI*((double) rand())/RAND_MAX;
   dcmplx c(cos(e),sin(e));
   return c;
}
class ComputePowers
{
   vector<dcmplx>  c; // numbers on input
   int d;           // degree
   vector<dcmplx>  result;  // output
   public:
      ComputePowers(vector<dcmplx> x, int deg, vector<dcmplx> y): c(x), d(deg), result(y) { }
      void operator() ( const blocked_range<size_t>& r ) const
      {
         for(int i=r.begin(); i!=r.end(); ++i)
         {
            dcmplx z(1.0,0.0);
            for(int j=0; j < d; j++) {
                z = z*c[i];
            };
            result[i] = z;
         }
      }
};
int main ( int argc, char *argv[] )
{
   int deg = 100;
   int dim = 10;
   vector<dcmplx> r;
   for(int i=0; i<dim; i++)
     r.push_back(random_dcmplx());
   vector<dcmplx> s(dim);
   task_scheduler_init init(task_scheduler_init::automatic);
   parallel_for(blocked_range<size_t>(0,dim),
                ComputePowers(r,deg,s));
   for(int i=0; i<dim; i++)
       cout << scientific << setprecision(4)
       << "x[" << i << "] = ( " << s[i].real()
       << " , " << s[i].imag() << ")n";
   return 0;
}

您正在尝试修改const限定的operator()中的非mutable成员字段result

解决此差异。

编辑#1:我已经提到了上面的两个关键字。任一:

  1. operator():中删除const限定符

    void operator() ( const blocked_range<size_t>& r ) { ... }
    
  2. 制作result mutable:

    mutable vector<dcmplx> result;
    

应用1号变体后可能会出现额外的erorrs(尽管强烈推荐)。第2个只是为了完整性,只在边缘情况下使用。

它确实导致了第一种变体的错误。这是因为tbb::parallel_forconst&Func,所以它只能在函子上调用const限定的成员函数。为什么?TBB不想通过复制大型函子来浪费性能(STL通过值传递它们)。

我不知道这里的惯例是什么,我从来没有用过这个图书馆。


编辑#2:可能您所缺少的只是result不是引用:

vector<dcmplx> &result;

现在,您可以修改它,即使是在符合const条件的operator()中。修改一个随后被销毁的成员是没有意义的。

不要忘记更改构造函数的签名以通过引用传递y


代码中的主题外问题:

  • 不包括<vector>标头

  • using namespace bulky_namespace全球

  • for环路中不使用size_t代替i

  • 也许更多。。。

相关文章: