OpenMP basics
| Parallel regions | |
| Parallel loops | |
| Private vs shared | |
| Measure speedup |
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, run with one thread and then with several, and divide the first time by the second.
Expect gains only on large loops: tiny loops can run slower in parallel because thread management itself takes time.
gfortran -fopenmp demo.f90 -o demo
serial time 4.0 s, 4 threads time 1.1 s, speedup about 3.6
Next: Namelists
Article author: Arthur Isaev