
This recommendation is part of the open catalog of best practice rules for performance that is automatically detected and reported by Codee.
Issue
Explicitly declare the scope of each variable used in a OpenMP parallel region to prevent an invalid default scoping being assigned to it.
Relevance
When the scope for a variable is not specified in an OpenMP parallel
region, a default scope is assigned to it. This default scope can be wrong, for instance sharing a variable that should be private, which can lead to a race condition. Furthermore, it ensures that the scope of each variable has been determined and improves code readability.
Actions
Declare the scope of each variable through the appropriate OpenMP clause.
Code example
In the following code, a variable factor
is used in each iteration of the loop to initialize the array result
.
void foo() {
int factor = 42;
int result[10];
#pragma omp parallel for
for (int i = 0; i < 10; i++) {
result[i] = factor * i;
}
}
Having the scope declared explicitly for each variable improves readability since it makes explicit the scope of all the variables within the parallel region.
void foo() {
int factor = 42;
int result[10];
#pragma omp parallel for shared(result, factor)
for (int i = 0; i < 10; i++) {
result[i] = factor * i;
}
}
Related resources
- PWR004 examples at GitHub
- PWR005: Disable default OpenMP scoping
- OpenMP 4.5 Complete Specifications, November 2015 [last checked May 2019]
References

Building performance into the code from day one with Codee