OpenMP basics
Parallel regions
An OpenMP parallel region is a block where a team of threads runs the same code together instead of one thread alone.
Directives are comments that start with exclamation omp, so a compiler without OpenMP support simply ignores them.
The sketch below prints one line per thread inside the region and continues with one thread after it.
program demo
implicit none
!$omp parallel
print *, "hello from a thread"
!$omp end parallel
print *, "back to one thread"
end program demo
Parallel loops
The parallel do directive splits loop iterations across the team, giving each thread a share of the work.
It fits loops with independent iterations, such as filling an array where each step writes only its own element.
The loop below doubles one thousand elements with the iterations shared automatically.
program demo
implicit none
integer :: i
real :: a(1000)
a = 1.0
!$omp parallel do
do i = 1, 1000
a(i) = 2.0 * a(i)
end do
!$omp end parallel do
print *, a(1), a(1000)
end program demo
Private vs shared
A shared variable is one copy seen by all threads, while a private variable gives every thread its own copy.
Keep big arrays shared so threads divide the real work, and make loop scratch values private so threads never clash over them.
The directive below shares the array a and gives each thread a private index i and scratch value t.
program demo
implicit none
integer :: i
real :: a(1000), t
a = 0.0
!$omp parallel do private(i, t) shared(a)
do i = 1, 1000
t = 0.5 * i
a(i) = t * t
end do
!$omp end parallel do
print *, a(1000)
end program demo
Measure speedup
Speedup compares the time of the serial version with the time of the parallel version on the same input data.
Enable OpenMP with the compiler flag shown below, then set OMP_NUM_THREADS to one and to four and time the same run with time.
Expect gains only on large loops: tiny loops can run slower in parallel because thread management itself takes time, and a container may have fewer cores than the machine it runs on.
gfortran -fopenmp demo.f90 -o demo
OMP_NUM_THREADS=4 ./demo
250000.000
The code on this page was run with gfortran 15.2.0 and OpenMP on four threads on Alpine Linux 3.24 (x86_64) in a Docker container.
Article author: Arthur Isaev