Purpose
The ORDERED / END ORDERED directives cause the iterations of a block of code within a parallel loop to be executed in the order that the loop would execute in if it was run sequentially. You can force the code inside the ORDERED construct to run in a predictable order while code outside of the construct runs in parallel.
The ORDERED and END ORDERED directives only take effect if you specify the -qsmp compiler option.
Format
>>-ORDERED----------------------------------------------------->< >>-block------------------------------------------------------->< >>-END ORDERED------------------------------------------------->< |
Rules
The ORDERED directive can only appear in the dynamic extent of a DO or PARALLEL DO directive. It is illegal to branch into or out of an ORDERED construct.
The ORDERED directive binds to the nearest dynamically enclosing DO or PARALLEL DO directive. You must specify the ORDERED clause on the DO or PARALLEL DO directive to which the ORDERED construct binds.
ORDERED constructs that bind to different DO directives are independent of each other.
Only one thread can execute an ORDERED construct at a time. Threads enter the ORDERED construct in the order of the loop iterations. A thread will enter the ORDERED construct if all of the previous iterations have either executed the construct or will never execute the construct.
Each iteration of a parallel loop with an ORDERED construct can only execute that ORDERED construct once. Each iteration of a parallel loop can execute at most one ORDERED directive. An ORDERED construct cannot appear within the dynamic extent of a CRITICAL construct.
Examples
Example 1: In this example, an ORDERED parallel loop counts down.
PROGRAM P !$OMP PARALLEL DO ORDERED DO I = 3, 1, -1 !$OMP ORDERED PRINT *,I !$OMP END ORDERED END DO END PROGRAM P
The expected output of this program is:
3 2 1
Example 2: This example shows a program with two ORDERED constructs in a parallel loop. Each iteration can only execute a single section.
PROGRAM P !$OMP PARALLEL DO ORDERED DO I = 1, 3 IF (MOD(I,2) == 0) THEN !$OMP ORDERED PRINT *, I*10 !$OMP END ORDERED ELSE !$OMP ORDERED PRINT *, I !$OMP END ORDERED END IF END DO END PROGRAM P
The expected output of this program is:
1 20 3
Example 3: In this example, the program computes the sum of all elements of an array that are greater than a threshold. ORDERED is used to ensure that the results are always reproducible: roundoff will take place in the same order every time the program is executed, so the program will always produce the same results.
PROGRAM P REAL :: A(1000) REAL :: THRESHOLD = 999.9 REAL :: SUM = 0.0 !$OMP PARALLEL DO ORDERED DO I = 1, 1000 IF (A(I) > THRESHOLD) THEN !$OMP ORDERED SUM = SUM + A(I) !$OMP END ORDERED END IF END DO END PROGRAM P
Related Information