openMP increment在线程中添加int?

时间:2018-02-09 00:13:13

标签: c++ multithreading concurrency openmp

我试图多线程以下功能。我没有让计数器在OpenMP线程之间正确共享,我尝试了原子和int,原子似乎不工作,INT也没有。不确定,我迷路了,我怎么能解决这个问题?

  std::vector<myStruct> _myData(100);
    int counter;
    counter =0
    int index;
#pragma  omp parallel for private(index)
    for (index = 0; index < 500; ++index) {
        if (data[index].type == "xx") {
            myStruct s;
            s.innerData = data[index].rawData
            processDataA(s); // processDataA(myStruct &data)
            processDataB(s);
            _myData[counter++] = s; // each thread should have unique int not going over 100 of initially allocated items in _myData
        }
    }

编辑。更新错误的语法/缺少部分

1 个答案:

答案 0 :(得分:0)

如果您无法使用OpenMP atomic capture,我会尝试:

std::vector<myStruct> _myData(100);
int counter = 0;
#pragma omp parallel for schedule(dynamic)
for (int index = 0; index < 500; ++index) {
   if (data[index].type == "xx") {
      myStruct s;
      s.innerData = data[index].rawData
      processDataA(s); 
      processDataB(s);
      int temp;
      #pragma omp critical
      temp = counter++;
      assert(temp < _myData.size());
      _myData[temp] = s; 
   }
}

或者:

#pragma omp parallel for schedule(dynamic,c)

并尝试使用块大小c

然而,原子可能比关键部分更有效。编译器应该支持某种形式的原子。

请注意,您的解决方案有点脆弱,因为只有当循环内的条件评估为true小于101x时,它才有效。这就是我在代码中加入断言的原因。也许是一个更好的解决方案:

std::vector<myStruct> _myData;
size_t size = 0;
#pragma omp parallel for reduction(+,size)
for (int index = 0; index < data.size(); ++index)
   if (data[index].type == "xx") size++;
v.resize(size);
...

然后,您不需要关心矢量大小,也不会浪费内存空间。