PRIVATE, FIRSTPRIVATE, and LASTPRIVATE Clauses

PRIVATE

Use the PRIVATE clause on the PARALLEL, DO, SECTIONS, SINGLE, PARALLEL DO, and PARALLEL SECTIONS directives to declare variables to be private to each thread in the team.

The behavior of variables declared PRIVATE is as follows:

In the following example, the values of I and J are undefined on exit from the parallel region:

Example

INTEGER I,J
I =1
J =2
!$OMP PARALLEL PRIVATE(I) FIRSTPRIVATE(J)
I =3
J =J+ 2
!$OMP END PARALLEL
PRINT *, I, J

FIRSTPRIVATE

Use the FIRSTPRIVATE clause on the PARALLEL, DO, SECTIONS, SINGLE, PARALLEL DO, and PARALLEL SECTIONS directives to provide a superset of the PRIVATE clause functionality.

In addition to the PRIVATE clause functionality, private copies of the variables are initialized from the original object existing before the parallel construct.

LASTPRIVATE

Use the LASTPRIVATE clause on the PARALLEL, DO, SECTIONS, SINGLE, PARALLEL DO, and PARALLEL SECTIONS directives to provide a superset of the PRIVATE clause functionality.

When the LASTPRIVATE clause appears on a DO PARALLEL DO directive, the thread that executes the sequentially last iteration updates the version of the object it had before the construct.

When the LASTPRIVATE clause appears on a SECTIONS or PARALLEL SECTIONS directive, the thread that executes the lexically last section updates the version of the object it had before the construct.

Sub-objects that are not assigned a value by the last iteration of the DO loop or the lexically last SECTION directive are undefined after the construct.

Correct execution sometimes depends on the value that the last iteration of a loop assigns to a variable. You must list all such variables as arguments to a LASTPRIVATE clause so that the values of the variables are the same as when the loop is executed sequentially. As shown in the following example, the value of I at the end of the parallel region is equal to N+1, as it would be with sequential execution.

Example

!$OMP PARALLEL
!$OMP DO LASTPRIVATE(I)
DO I=1,N
 A(I) = B(I) + C(I)
END DO
!$OMP END PARALLEL
CALL REVERSE(I)