DO CONCURRENT
| Loop without order | |
| Locality specs | |
| Reductions | |
| Offload note (conceptual) |
Loop without order
A do concurrent loop states that iterations have no required order, so the compiler may run them in any sequence or in parallel.
Use it only when iterations are truly independent: each step must write its own element and never depend on a neighbor step.
The loop below doubles every element, and any iteration order gives the same array.
program demo
implicit none
integer :: i
real :: a(100)
a = 1.0
do concurrent (i = 1:100)
a(i) = 2.0 * a(i)
end do
print *, a(1), a(100)
end program demo
Locality specs
Locality specs declare which variables are private to each iteration and which are shared across all of them.
A temporary scratch variable belongs in local, while the array being computed stays shared by default.
The example gives every iteration its own copy of t, so parallel steps cannot overwrite each other scratch value.
program demo
implicit none
integer :: i
real :: a(100), t
a = 0.0
do concurrent (i = 1:100) local(t)
t = 0.5 * i
a(i) = t * t
end do
print *, a(100)
end program demo
Reductions
A reduction combines one value from every iteration with an operator such as plus, and the reduce clause makes that intent explicit.
Each iteration works on a private partial result, and the compiler merges the parts safely at the end of the loop.
The loop below sums one hundred elements without any manual synchronization.
program demo
implicit none
integer :: i
real :: a(100), s
a = 1.0
s = 0.0
do concurrent (i = 1:100) reduce(+:s)
s = s + a(i)
end do
print *, s
end program demo
Offload note (conceptual)
Some compilers can offload do concurrent loops to a graphics processor, but that ability depends on the compiler and its flags.
Treat offload as a bonus rather than a promise: write a correct order-free loop first, then study the compiler manual for the offload option.
The conceptual build below shows where such a flag would appear, with no claim about any specific machine in this lesson.
gfortran -O2 demo.f90 -o demo
build ok, run on the host CPU
Next: Coarrays
Article author: Arthur Isaev