0
votes

I am a bit confused if there is a data race for variable k. To my understanding, only one thread will execute the single construct but since no wait is asserted, threads will start executing the for construct immediately. Is atomic here enough to prevent any potential data race?

#include <stdio.h>
#include <omp.h>
#define Nthreads 8

void main()
{

int n =9, l,k =n,i,j;
k += n+1;

omp_set_num_threads(Nthreads);

  #pragma omp parallel default(none) shared(n, k) private(j)
  {
   #pragma omp single nowait
    {
    k = k+5;
    }
   #pragma omp for nowait
     for( i =0; i< n; i++)
     {
      #pragma omp atomic
       k +=n+i+1;
     }
  }   
}
1
Having atomic in both worksharing constructs should suffice. You may also explicitly use atomic update to make your intent clearer to the reader. - Hristo Iliev
Do you mean I should add atomic inside single construct as well? - FATzz
He means using an atomic in both places ( single and for ) as well as explicitly specifying the update atomic clause which is now implicitly used at the atomic synchronization construct. Being explicit is a matter of preference though, it will not change the output of the code. - pattakosn

1 Answers

1
votes

Assuming the rest of the code expresses your intended algorithm correctly, it almost is. As you were probably suspecting yourself, you need to protect k' s update in the single region as well.

j is an unused variable, I do not know if you simply forgot to delete it or you were trying to implement sth else.

I would have used a reduction clause for k in the for loop instead of using a synchronization construct. I do not know if it would have been better or faster though.