Variable
Scoping Inside OpenMP Parallel Regions
One of the trickier aspects of parallelization is the scoping of
variables used in the parallel region. In Listing 7.24, there are four
variables used in the parallel region: i, length, array1, and array2. The
variables can be scoped either as shared, so each thread shares the same variable, or as private, where each thread gets its own
copy of the variable.
The loop counter i needs to be private to each thread so that each thread gets its own
copy of the variable. The variables array1 and array2 are
shared. Each thread works on a separate range of values, so there is no actual
sharing of data. The variable length is also
shared between the threads, but since it is not modified, it does not mat-ter
whether it is scoped as shared or private. It is possible to see how the
Solaris Studio compiler has scoped these variables using the code analysis tool
er_src on the
gener-ated object file, as shown in Listing 7.24.
Listing 7.24 Using er_src to Examine Variable Scoping for Parallel Region
% cc -c -g -O -xopenmp -xloopinfo omploop.c "omploop.c", line 4: PARALLELIZED, user pragma used
% er_src omploop.o
...
1.void calc( double * array1, double * array2, int
length )
2.{
<Function:
calc>
Source OpenMP region below has tag R1
Private
variables in R1: i
Shared variables in R1: array2, length, array1
3. #pragma omp parallel for
Source loop below has tag L1
L1 parallelized by explicit user directive
...
4. for(
int i=0; i<length; i++ )
5. {
6. array1[i]
+= array2[i];
7. }
}
The rules governing the default variable scoping in OpenMP are quite
complex. The simplified summary of the rules is that they define the loop
induction variable as being private, variables defined in the parallel code as
being private, and variables defined out-side the parallel region as being
shared. This should be appropriate in simple situations but may not be
appropriate in more complex ones. In these situations, it is better to manually
define the variable scoping. The default scoping rules can be disabled using
the clause default(none), which
will cause the compiler to issue an error for any variables whose scoping is
not specified. Variables can be scoped as private or shared using the clause private(variables) or shared(variables),
respectively. Listing 7.25 shows the original source modified to manually
specify variable scoping.
Listing 7.25 Loop
Parallelized Using OpenMP with Explicitly Stated Variable Scoping
void calc( double* array1, double * array2, int length )
{
int i;
#pragma omp
parallel for private(i) shared(length, array1, array2)
for ( i=0; i<length; i++ )
{
array1[i] += array2[i];
}
}
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.