DO CONCURRENT

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. The reduce clause arrived in Fortran 2023, so ask for that standard with -std=f2023; the default gfortran mode accepts it as well.

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 build below is the ordinary optimised one: it stays on the host CPU and prints the same sum.

gfortran -O2 -std=f2023 demo.f90 -o demo && ./demo

100.000000

The code on this page was run with gfortran 15.2.0 on Alpine Linux 3.24 (x86_64) in a Docker container.

Article author: Arthur Isaev