Home > other >  beginner question: openMP for a loop that uses its own data
beginner question: openMP for a loop that uses its own data

Time:12-20

Sorry if the title is not decsribing this accurately! I am new to OMP and trying to make this loop parallel. I am struggling with critical, atomic and locks but can't get it to work. b is an array of doubles with size n.

The result is not the same as when I remove the omp code

My real code is more ocmplex but if I can understand the use of OMP on this it would be a great help

#pragma omp parallel
 for(int i = 0; i < n; i  ) 
 {
    double v = 0;
     
    #pragma omp critical
    for (int j=i-1; j <= i 1; j  )
       if (j >= 0 && j < n)
           v  = b[j];
   
    b[i] = somecalculation(v);
 }

CodePudding user response:

There are two issues here:

  1. You use #pragma omp parallel but it looks like you want #pragma omp parallel for. The way you have written it, every thread executed every iteration of the loop, practically calculating everything multiple times

  2. Your critical section ends after the loop. It does not cover the update of b[i]. However, the calculation of i 1 depends on the result of i

How to fix this: I don't think you can. The code doesn't seem parallelizable in any meaningful way because every iteration depends on the result of the last one.

CodePudding user response:

sorry, I do have for in reality. With critical extneded to include the calculation of b[i] I get the same wrong result. I guess you are right, not paralizable, I just hoped there would be some trick!

#pragma omp parallel for
 for(int i = 0; i < n; i  ) 
 {
    double v = 0;
     
    #pragma omp critical
   {
     for (int j=i-1; j <= i 1; j  )
       if (j >= 0 && j < n)
           v  = b[j];
   
     b[i] = somecalculation(v);
   }
 }
  • Related