Maghio
Maghio

Reputation: 385

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.

Upvotes: 2

Views: 411

Answers (2)

Maghio
Maghio

Reputation: 385

Finally this should be the code to get every thread prints "n=1":

int main()
{
    int n=0, t;

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

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

            #pragma omp barrier
            printf("Sono %d e ho n = %d\n", t, n);
    }

    return 0;

}

Thanks to fuesika.

Upvotes: 0

fuesika
fuesika

Reputation: 3330

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.

Upvotes: 1

Related Questions