0

短い外側のループと長い内側のループを実行する必要があります。前者ではなく後者を並列化したいと思います。その理由は、内側のループが実行された後に更新される配列があるためです。私が使用しているコードは次のとおりです

#pragma omp parallel{
for(j=0;j<3;j++){
  s=0;
  #pragma omp for reduction(+:s)
     for(i=0;i<10000;i++)
        s+=1;

  A[j]=s;
}
}

これは実際にハングします。以下は問題なく機能しますが、新しい並列領域を開始するオーバーヘッドは避けたいと思います。

for(j=0;j<3;j++){
  s=0;
  #pragma omp parallel for reduction(+:s)
     for(i=0;i<10000;i++)
        s+=1;

  A[j]=s;

}

これを行う正しい(そして最速の)方法は何ですか?

4

1 に答える 1

1

次の例は、期待どおりに動作するはずです。

#include<iostream>

using namespace std;

int main(){

  int s;
  int A[3];

#pragma omp parallel
  { // Note that I moved the curly bracket
    for(int j = 0; j < 3; j++) {
#pragma omp single         
      s = 0;
#pragma omp for reduction(+:s)
      for(int i=0;i<10000;i++) {
        s+=1;
      } // Implicit barrier here    
#pragma omp single
      A[j]=s; // This statement needs synchronization
    } // End of the outer for loop
  } // End of the parallel region

  for (int jj = 0; jj < 3; jj++)
    cout << A[jj] << endl;
  return 0;
}

コンパイルと実行の例は次のとおりです。

> g++ --version
g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
> g++ -fopenmp -Wall main.cpp
> export OMP_NUM_THREADS=169
> ./a.out 
10000
10000
10000
于 2013-05-13T13:10:46.957 に答える