Fortran Parallelism
Most Fortran code runs on parallel hardware, from multi-core laptops to supercomputers with millions of cores. There are four main tools, often combined: the compiler's auto-vectorisation of array syntax and do concurrent, OpenMP for threads on one machine, MPI for many machines, and Fortran's own built-in coarrays. This lesson introduces each one conceptually. The playground runs programs on a single core without these libraries, so the parallel examples are shown as non-runnable code with the output you'd see.
Level 0: write code the compiler can parallelise
Array expressions, elemental and pure procedures and do concurrent all tell the compiler that operations are independent. With optimisation on (-O3 -march=native) it turns them into SIMD vector instructions, and some compilers can even offload do concurrent to multiple cores or GPUs (nvfortran -stdpar=gpu, ifx -fopenmp with do concurrent, or gfortran's -ftree-parallelize-loops=N).
program vector_friendly
use iso_fortran_env, only: dp => real64
implicit none
integer, parameter :: n = 1000000
real(dp), allocatable :: x(:), y(:)
real(dp) :: a
integer :: i
allocate(x(n), y(n))
a = 2.5_dp
do concurrent (i = 1:n)
x(i) = real(i, dp) / n
end do
y = 1.0_dp
y = a * x + y ! the classic "axpy": easily vectorised
print '(a, f14.6)', 'sum(y) = ', sum(y)
print '(a, 3f10.6)', 'first values: ', y(1:3)
end program vector_friendlysum(y) = 2250001.250000
first values: 1.000002 1.000005 1.000007
This program is already parallel-ready: every element is computed independently, and nothing in the code depends on the order.
OpenMP: threads on one machine
OpenMP adds parallelism with special comments, directives starting with !$omp. Without the compiler flag (-fopenmp) they are just comments, so the same source still builds as a serial program.
program omp_sum
use omp_lib
implicit none
integer, parameter :: n = 100000000
integer :: i
real(8) :: total
total = 0.0d0
!$omp parallel do reduction(+:total)
do i = 1, n
total = total + 1.0d0 / (real(i, 8)**2)
end do
!$omp end parallel do
print '(a, f12.9)', 'sum 1/i^2 = ', total ! approaches pi^2/6
print '(a, i0)', 'threads used: ', omp_get_max_threads()
end program omp_sumgfortran -O2 -fopenmp omp_sum.f90 -o omp_sum
OMP_NUM_THREADS=8 ./omp_sumsum 1/i^2 = 1.644934057
threads used: 8!$omp parallel dosplits the loop iterations among threads.reduction(+:total)gives every thread its own partial sum and adds them at the end. Without it, threads would updatetotalat the same time: a race condition with unpredictable results.private(tmp)gives each thread its own copy of a scratch variable; loop indices are private automatically.- The number of threads comes from
OMP_NUM_THREADSoromp_set_num_threads.
Note: Because floating-point addition is not associative, a parallel reduction can differ from the serial sum in the last digits, and may vary slightly with the number of threads.
OpenMP also offers tasks, !$omp critical sections, !$omp atomic updates, and (since 4.0) !$omp target directives that offload loops to GPUs.
MPI: many machines
On a cluster, each node has its own memory. MPI (Message Passing Interface) runs many copies of the program, called ranks, which cooperate by explicitly sending messages. The mpi_f08 module provides a modern, type-checked Fortran interface:
program mpi_hello
use mpi_f08
implicit none
integer :: rank, nprocs
real :: local, global
call MPI_Init()
call MPI_Comm_rank(MPI_COMM_WORLD, rank)
call MPI_Comm_size(MPI_COMM_WORLD, nprocs)
local = real(rank + 1) ! each rank computes a partial result
call MPI_Reduce(local, global, 1, MPI_REAL, MPI_SUM, 0, MPI_COMM_WORLD)
if (rank == 0) print '(a, i0, a, f6.1)', 'ranks: ', nprocs, ', total: ', global
call MPI_Finalize()
end program mpi_hellompifort mpi_hello.f90 -o mpi_hello
mpirun -np 4 ./mpi_helloranks: 4, total: 10.0Large simulation codes typically decompose the domain into blocks, one per rank, and exchange the boundary layers ("halos") with neighbours each time step.
Coarrays: parallelism built into the language
Fortran 2008 made parallel programming part of the language itself. A coarray program runs as several images (copies) at once. Variables declared with square brackets, real :: x[*], are coarrays: every image has its own x, and any image can read or write another image's copy with x[n].
program coarray_sum
implicit none
real :: partial[*] ! one copy per image
real :: total
integer :: i, me, n
me = this_image() ! 1 .. num_images()
n = num_images()
partial = sum([(real(i), i = me, 1000, n)]) ! each image sums its share of 1..1000
sync all ! wait until every image has finished
if (me == 1) then
total = 0.0
do i = 1, n
total = total + partial[i] ! read another image's value
end do
print '(a, i0, a, f8.1)', 'images: ', n, ', sum 1..1000 = ', total
end if
end program coarray_sum# gfortran needs OpenCoarrays for real parallel runs:
caf coarray_sum.f90 -o coarray_sum && cafrun -n 4 ./coarray_sum
# or single-image mode, for testing: gfortran -fcoarray=single coarray_sum.f90images: 4, sum 1..1000 = 500500.0Fortran 2018 added collective subroutines that make this simpler: call co_sum(partial) sums a variable across all images in one call, and there are co_max, co_min, co_broadcast and co_reduce. Intel ifx supports coarrays out of the box (-coarray), and they map onto MPI underneath.
Choosing a model
| Model | Scale | Memory | Effort |
|---|---|---|---|
array syntax / do concurrent |
one core (SIMD), sometimes many | shared | lowest: just clean code |
| OpenMP | one node, many threads | shared | low: add directives |
| coarrays | one node to clusters | distributed, language-level | medium |
| MPI | clusters, supercomputers | distributed, explicit messages | highest, most control |
Real HPC codes often use MPI + OpenMP (MPI between nodes, threads within a node) and offload hot loops to GPUs. Whatever the model, the design principle is the same: find work that can be done independently, and minimise how much data must move between workers.
Test yourself
What happens to !$omp directives when you compile without -fopenmp?
- Compile error
- They are treated as comments and the program runs serially
- They run with one thread per core anyway
- They are converted to MPI calls
Why does a parallel sum need reduction(+:total)?
- To make it faster
- To avoid a race condition where threads update
totalsimultaneously - To print the result
- It isn't needed
In coarray Fortran, what does x[3] refer to?
- Element 3 of array x
- The copy of coarray x on image 3
- x cubed
- The third thread's stack