Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 751
argoneus Avatar asked Oct 12 '11 04:10

argoneus


People also ask

What does private do in OpenMP?

The private clause declares the variables in the list to be private to each thread in a team. The firstprivate clause provides a superset of the functionality provided by the private clause. The private variable is initialized by the original value of the variable when the parallel construct is encountered.

What is shared and private in OpenMP?

A variable in an OpenMP parallel region can be either shared or private. If a variable is shared, then there exists one instance of this variable which is shared among all threads. If a variable is private, then each thread in a team of threads has its own local copy of the private variable.

What is private clause in OpenMP?

private. Specifies that each thread should have its own instance of a variable. firstprivate. Specifies that each thread should have its own instance of a variable, and that the variable should be initialized with the value of the variable, because it exists before the parallel construct.

What is OMP parallel sections in OpenMP?

The omp parallel sections directive effectively combines the omp parallel and omp sections directives. This directive lets you define a parallel region containing a single sections directive in one step.


1 Answers

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".
    }
like image 89
Mysticial Avatar answered Oct 19 '22 07:10

Mysticial