# Rules for Nesting and Binding

This section describes the dynamic nesting and binding rules for OpenMP* Fortran API directives.

## Binding Rules

The following rules apply to dynamic binding:

- The DO, SECTIONS, SINGLE, MASKED, MASTER, and BARRIER directives bind to the dynamically enclosing PARALLEL directive, if one exists.

- The ORDERED directive binds to the dynamically enclosing DO directive.

- The ATOMIC directive enforces exclusive access with respect to ATOMIC directives in all threads, not just the current team.

- The CRITICAL directive enforces exclusive access with respect to CRITICAL directives in all threads, not just the current team.

- A directive can never bind to any directive outside the closest enclosing PARALLEL directive.

## Nesting Rules

The following rules apply to dynamic nesting:

- A PARALLEL directive dynamically inside another PARALLEL directive logically establishes a new team, which is composed of only the current thread unless nested parallelism is enabled.

- DO, SECTIONS, and SINGLE directives that bind to the same PARALLEL directive are not allowed to be nested one inside the other.

- DO, SECTIONS, and SINGLE directives are not permitted in the dynamic extent of CRITICAL, MASKED, and MASTER directives.

- BARRIER directives are not permitted in the dynamic extent of DO, SECTIONS, SINGLE, MASKED, MASTER, and CRITICAL directives.

- MASKED and MASTER directives are not permitted in the dynamic extent of DO, SECTIONS, and SINGLE directives.

- ORDERED sections are not allowed in the dynamic extent of CRITICAL sections.

- Any directive set that is legal when executed dynamically inside a PARALLEL region is also legal when executed outside a parallel region. When executed dynamically outside a user-specified parallel region, the directive is executed with respect to a team composed of only the primary thread.

## Examples

The following example shows nested PARALLEL regions:

      !$OMP PARALLEL DEFAULT(SHARED)
      !$OMP DO
              DO I =1, N
      !$OMP PARALLEL SHARED(I,N)
      !$OMP DO
              DO J =1, N
                CALL WORK(I,J)
              END DO
      !$OMP END PARALLEL
            END DO
      !$OMP END PARALLEL

Note that the inner and outer DO directives bind to different PARALLEL regions.

The following shows a variation of the preceding example:

      !$OMP PARALLEL DEFAULT(SHARED)
      !$OMP DO
              DO I =1, N
                 CALL SOME_WORK(I,N)
              END DO
      !$OMP END PARALLEL
            ...
            SUBROUTINE SOME_WORK(I,N)
      !$OMP PARALLEL DEFAULT(SHARED)
      !$OMP DO
              DO J =1, N
                 CALL WORK(I,J)
              END DO
      !$OMP END PARALLEL
              RETURN
              END

Parent topic: OpenMP* Fortran Compiler Directives