OPEN CATALOG

Best practices for performance

PWR004: Declare OpenMP scoping for all variables

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 #

References #