Home > Back-end >  Why does the result of #pragma omp parallel look like this
Why does the result of #pragma omp parallel look like this

Time:02-12

    #include<stdio.h>

    int main()
    {
        int a=0, b=0;
        #pragma omp parallel num_threads(16)
        {
            // #pragma omp single
            a  ;
            // #pragma omp critical
            b  ;
        }
        printf("single: %d -- critical: %d\n", a, b);
    }

Why is my output single: 5 -- critical: 5 here?
And why is it output single: 3 -- critical: 3 when num_threads(4)?

I should not code anything like this, right? If the threads are confused here (I guess), why the result is consistent?

CodePudding user response:

That's just pure luck, helped by inherent timing of the operation. Since this is the first parallel section in your program, threads are built instead of reused. That occupies the main thread for a while and results in threads starting sequentially. Therefore the chance of overlapping operations is lower. Try adding a #pragma omp barrier in between to increase the chance of race conditions becoming apparent.

CodePudding user response:

You have race conditions, therefore the values of a and b are undefined. To correct it you can

a) use reduction (it is the best solution):

#pragma omp parallel num_threads(16) reduction( :a,b)

b) use atomic operations (generally it is less efficient):

#pragma omp atomic 
   a  ;
#pragma omp atomic
   b  ;

c) use critical section (i.e. locks, which is the worst solution):

#pargma omp critical
{
   a  ;
   b  ;
}
  • Related