argoneus
argoneus

Reputation: 731

Are pointers private in OpenMP parallel sections?

I've added OpenMP to an existing code base in order to parallelize a for loop. Several variables are created inside the scope of the parallel for region, including a pointer:

#pragma omp parallel for
for (int i = 0; i < n; i++){
    [....]
    Model *lm;
    lm->myfunc();
    lm->anotherfunc();
    [....]
}

In the resulting output files I noticed inconsistencies, presumably caused by a race condition. I ultimately resolved the race condition by using an omp critical. My question remains, though: is lm private to each thread, or is it shared?

Upvotes: 9

Views: 4409

Answers (1)

Mysticial
Mysticial

Reputation: 471199

Yes, all variables declared inside the OpenMP region are private. This includes pointers.

Each thread will have its own copy of the pointer.

It lets you do stuff like this:

int threads = 8;
int size_per_thread = 10000000;

int *ptr = new int[size_per_thread * threads];

#pragma omp parallel num_threads(threads)
    {
        int id = omp_get_thread_num();
        int *my_ptr = ptr + size_per_thread * id;

        //  Do work on "my_ptr".
    }

Upvotes: 11

Related Questions