Home > Software design >  OpenMP: are variables automatically shared?
OpenMP: are variables automatically shared?

Time:10-24

We already know that local variables are automatically private.

int i,j;
#pragma omp parallel for private(i,j)
for(i = 0; i < n; i  ) {
    for(j = 0; j < n; j  ) {
        //do something
    }
}

it is equal to

#pragma omp parallel for
for(int i = 0; i < n; i  ) {
    for(int j = 0; j < n; j  ) {
        //do something
    }
}

How about the other variables ? are they shared by default or do we need to specify shared() like in the example below ?

bool sorted(int *a, int size)
{
  bool sorted = true;
#pragma omp parallel default(none) shared(a, size, sorted)
  {
#pragma omp for reduction (&:sorted)
    for (int i = 0; i < size - 1; i  ) sorted &= (a[i] <= a[i   1]);
  }
  return sorted;
}

Can we not specify the shared and work directly with our (a, size, sorted) variables ?

CodePudding user response:

They are shared by default in a parallel section unless there is a default clause specified. Note that this is not the case for all OpenMP directives. For example, this is generally not the case for tasks. You can read that from the OpenMP specification:

In a parallel, teams, or task generating construct, the data-sharing attributes of these variables are determined by the default clause, if present (see Section 5.4.1).

  • In a parallel construct, if no default clause is present, these variables are shared.
  • For constructs other than task generating constructs, if no default clause is present, these variables reference the variables with the same names that exist in the enclosing context.
  • In a target construct, variables that are not mapped after applying data-mapping attribute rules (see Section 5.8) are firstprivate.

You can safely rewrite your code as the following:

bool sorted(int *a, int size)
{
    bool sorted = true;
    #pragma omp parallel for reduction(&:sorted)
    for (int i = 0; i < size - 1; i  )
       sorted &= a[i] <= a[i   1];
    return sorted;
}
  • Related