Are pointers private in OpenMP parallel sections?
I've开发者_Python百科 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?
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".
}
精彩评论