OpenMP while loop

后端 未结 1 1594
星月不相逢
星月不相逢 2021-01-06 20:25

I have a code that runs many iterations and only if a condition is met, the result of the iteration is saved. This is naturally expressed as a while loop. I am attempting to

相关标签:
1条回答
  • 2021-01-06 21:05

    You can basically follow the same concept as for this question, with a slight variation to ensure that avRes is not written to in parallel:

    int nit = 0;
    #pragma omp parallel
    while(1) {
         int local_nit;
         #pragma omp atomic read
         local_nit = nit;
         if (local_nit >= avit) {
              break;
         }
    
         [...]
    
         if (...) { 
              #pragma omp critical
              {
                    #pragma omp atomic capture
                    local_nit = ++nit;
                    for(j=0;j<jmax;j++){
                        avRes[j] += Res[j];
                    } 
                    for(j=0;j<jmax;j++){
                        // technically you could also use `nit` directly since
                        // now `nit` is only modified within this critical section
                        cout<<avRes[j]/local_nit<<"\t";
                    }
              }
         } else {
              #pragma omp atomic update
              dit++;
         }
     }
    

    It also works with critical regions, but atomics are more efficient.

    There's another thing you need to consider, rand() should not be used in parallel contexts. See this question. For C++, use a private (i.e. defined within the parallel region) random number generator from <random>.

    0 讨论(0)
提交回复
热议问题