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;
}
}
}
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.