Skip to main content

PWR005: Disable default OpenMP scoping

Issue​

Disable default OpenMP scoping to force having to declare the scoping of all variables.

Actions​

Add default(none) to disable default OpenMP scoping.

Relevance​

When the scope for a variable is not specified in an OpenMP parallel directive, a default scope is assigned to it. Even when set explicitly, using a default scope is considered a bad practice since it can lead to wrong data scopes inadvertently being applied to variables. Thus, it is recommended to explicitly set the scope for each variable.

Code example​

C​

In the following code, a variable t is used in each iteration of the loop to hold a value that is then assigned to the array result. Since no data scoping is declared for those variables, the default will be used. This makes the variable t shared, which is incorrect since it introduces a race condition:

void example() {
int t;
int result[10];

#pragma omp parallel for
for (int i = 0; i < 10; i++) {
t = i + 1;
result[i] = t;
}
}

The following code disables the default scoping, which will make the compiler raise an error due to unspecified scopes:

void example() {
int t;
int result[10];

#pragma omp parallel for default(none)
for (int i = 0; i < 10; i++) {
t = i + 1;
result[i] = t;
}
}

To fix the code, the scope of each variable must be specified. The variable t must be made private to prevent the race condition:

void example() {
int t;
int result[10];

#pragma omp parallel for default(none) shared(result) private(i, t)
for (int i = 0; i < 10; i++) {
t = i + 1;
result[i] = t;
}
}

Fortran​

In the following code, a variable t is used in each iteration of the loop to hold a value that is then assigned to the array result. Since no data scoping is declared for those variables, the default will be used. This makes the variable t shared, which is incorrect since it introduces a race condition:

subroutine example()
integer :: i, t
integer :: result(10)

!$omp parallel do
do i = 1, 10
t = i + 1;
result(i) = t;
end do
end subroutine example

The following code disables the default scoping, which will make the compiler raise an error due to unspecified scopes:

subroutine example()
integer :: i, t
integer :: result(10)

!$omp parallel do default(none)
do i = 1, 10
t = i + 1;
result(i) = t;
end do
end subroutine example

To fix the code, the scope of each variable must be specified. The variable t must be made private to prevent the race condition:

subroutine example()
integer :: i, t
integer :: result(10)

!$omp parallel do default(none) shared(result) private(i, t)
do i = 1, 10
t = i + 1;
result(i) = t;
end do
end subroutine example

References​