cparallel-processingopenmp

OpenMP shared variable seems to be private


I don't understand why in this code only the thread 0 has n = 1 while the other ones have n = 0 with shared n:

int main()
{
    int n, tid;

    #pragma omp parallel shared(n) private(tid)
    {
            tid = omp_get_thread_num();
            n = 0;

            if (tid == 0)
            {
                    n++;
            }

            printf("I'am %d, this is my n: %d\n", tid, n);
    }

    return 0;

}

Output:

I'am 5, this is my n: 0
I'am 7, this is my n: 0
I'am 0, this is my n: 1
I'am 2, this is my n: 0
I'am 4, this is my n: 0
I'am 3, this is my n: 0
I'am 6, this is my n: 0
I'am 1, this is my n: 0

I'm new with the OMP library. I'm working through ssh on a cluster with 8 nodes, could this be the problem?

Thank you.


Solution

  • You are practically resetting n to zero by each thread. Only the thread with tid==0 will increment n prior to printing. Even here, you may encounter the program to print

    I'am 0, this is my n: 0

    instead of the expected

    I'am 0, this is my n: 1

    since you produced a so-called race condition.

    If you intend initialize n with zero only at the beginning of runtime, you will need to initialize n earlier, e.g. prior to starting the parallel section:

    n = 0;
    
    #pragma omp parallel shared(n) private(tid)
    {
            tid = omp_get_thread_num();
    
            if (tid == 0)
            {
                    n++;
            }
    
            printf("I'am %d, this is my n: %d\n", tid, n);
    }
    

    Note, however, that the state of n in the printed list will then be somewhat random again, since you can never be sure when thread 0 increments the value of n to equal 1.