Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Programming with OpenMP

OpenMP is the simplest way to parallelize an existing code on a single node. By adding a few compiler directives to a serial program, you can distribute the work over all the cores of a shared memory machine, without rewriting your algorithms.

In this lecture, we will:

Parallel programming languages

Evolution of programming methods:

Distributed memory versus shared memory

OpenMP history

Multi-threading using directives

During the era of vector processing (mid-90s), many vendors (Cray, NEC, IBM...) were using their own multi-threading directives. On October 28th 1997, they all met and adopted the Open Multi-Processing standard. OpenMP is specified by the Architecture Review Board (ARB).

General concepts

Multi-threading

Compilation

An OpenMP program relies on three ingredients:

Example:

$ gfortran -fopenmp prog.f90
$ ifx -qopenmp prog.f90
$ export OMP_NUM_THREADS=4

Parallel region

Shared variables

program parallel
  !$ use OMP_LIB
  implicit none
  real    :: a
  logical :: p

  a = 92290. ; p=.false.
  !$OMP PARALLEL
  !$ p = OMP_IN_PARALLEL()
  print *,"A = ",a, &
          "; p = ",p
  !$OMP END PARALLEL
end program parallel
$ gfortran -fopenmp prog.f90
$ export OMP_NUM_THREADS=4
$ ./a.out
 A =    92290.0000     ; p =  T
 A =    92290.0000     ; p =  T
 A =    92290.0000     ; p =  T
 A =    92290.0000     ; p =  T

Lines starting with !$ are only compiled when OpenMP is enabled. This is called conditional compilation: without -fopenmp, the code above is still a valid serial program.

Private variables

program parallel
  implicit none
  real :: a

  a = 92000.
  !$OMP PARALLEL DEFAULT(PRIVATE)
    a = a + 290.
    print *,"A = ",a
  !$OMP END PARALLEL
end program parallel
$ gfortran -fopenmp prog.f90
$ export OMP_NUM_THREADS=4
$ ./a.out
 A =    290.000000
 A =    290.000000
 A =    290.000000
 A =               NaN

The value 92000 set before the parallel region is lost: each thread starts from an uninitialized copy of a, which here happened to contain 0 or NaN.

program parallel
  implicit none
  real :: a

  a = 92000.
  !$OMP PARALLEL DEFAULT(NONE) &
  !$OMP FIRSTPRIVATE(a)
    a = a + 290.
    print *,"A = ",a
  !$OMP END PARALLEL
  print*,"Out of region, A =",a
end program parallel
$ gfortran -fopenmp prog.f90
$ export OMP_NUM_THREADS=4
$ ./a.out
 A =    92290.0000
 A =    92290.0000
 A =    92290.0000
 A =    92290.0000
 Out of region, A =   92000.0000

Number of threads

program parallel
  implicit none

  !$OMP PARALLEL NUM_THREADS(2)
    print *,"Hello !"
  !$OMP END PARALLEL

  !$OMP PARALLEL NUM_THREADS(3)
    print *,"Hi !"
  !$OMP END PARALLEL
end program parallel
$ gfortran -fopenmp prog.f90
$ export OMP_NUM_THREADS=4
$ ./a.out
 Hello !
 Hello !
 Hi !
 Hi !
 Hi !

Parallel loop

Work decomposition

Work scheduling

Examples

With the default scheduling, the n=4096n = 4096 iterations are divided into 4 contiguous chunks of 1024 iterations, one per thread:

program parallel
  !$ use OMP_LIB
  implicit none
  integer, parameter :: n=4096
  real,dimension(n) :: a
  integer :: i, rank, nb_threads

  !$OMP PARALLEL PRIVATE(rank,nb_threads)
  rank=OMP_GET_THREAD_NUM()
  nb_threads=OMP_GET_NUM_THREADS()
  !$OMP DO
  do i=1,n
     print*,rank,i
     a(i) = 92290. + real(i)
  end do
  !$OMP END DO
  !$OMP END PARALLEL

end program parallel
$ gfortran -fopenmp prog.f90
$ export OMP_NUM_THREADS=4
$ ./a.out | more
           1        1025
           0           1
           3        3073
           2        2049
           1        1026
           0           2
           3        3074
           2        2050
...

With a STATIC schedule and a chunk size of 128, the iterations are distributed in a round-robin fashion by blocks of 128:

  !$OMP DO SCHEDULE(STATIC,128)
  do i=1,n
     print*,rank,i
     a(i) = 92290. + real(i)
  end do
  !$OMP END DO
$ ./a.out | more
           2         257
           0           1
           1         129
           3         385
           2         258
           0           2
           1         130
           3         386
...

With a RUNTIME schedule, the strategy is chosen at execution time with the OMP_SCHEDULE environment variable. Here, a GUIDED schedule starts with large chunks and decreases their size down to a minimum of 16:

  !$OMP DO SCHEDULE(RUNTIME)
  do i=1,n
     print*,rank,i
     a(i) = 92290. + real(i)
  end do
  !$OMP END DO
$ export OMP_SCHEDULE="GUIDED,16"
$ ./a.out | more
           0           1
           2        1025
           3        1793
           1        2369
           0           2
           2        1026
           3        1794
           1        2370
...

Synchronization and reductions

Reductions

program parallel
  implicit none
  integer, parameter :: n=5
  integer            :: i, s=0, p=1, r=1
  !$OMP PARALLEL
  !$OMP DO REDUCTION(+:s) REDUCTION(*:p,r)
    do i = 1, n
      s = s + 1
      p = p * 2
      r = r * 3
    end do
  !$OMP END PARALLEL
  print *,"s =",s, "; p =",p, "; r =",r
end program parallel

Barriers and race conditions

Best practices

Memory placement

Examples

The following examples can be found in the codes/ directory. They were run on an Apple M1 Max laptop with 8 performance cores.

Computing π\pi

We compute π\pi using the integral

π=4∫0111+x2 dx\pi = 4 \int_0^1 \frac{1}{1+x^2} \, dx

approximated with the rectangle rule using n=1010n = 10^{10} points. Each thread computes a partial sum over its own iterations, and the REDUCTION clause combines the partial sums at the end of the loop:

compute_pi_omp.f90
program compute_pi
  ! Declare and/or Initialize variables
  use omp_lib
  implicit none
  real(kind=8) :: pi = 4.d0*ATAN(1.d0)

  integer :: narg
  integer(kind=8) :: i, n
  real(kind=8) :: h = 1
  real(kind=8) :: strt, stop, x, integ
  character(len=80) :: arg

  ! Parse input
  narg = command_argument_count()
  if (narg .eq. 0) then
     n = int(1e10,kind=8)
  else if (narg .eq. 1) then
     call get_command_argument(1, arg)
     read(arg,*) n
  else
     write(*,*)  'Usage: ./compute_pi [n]'
     call exit(1)
  end if

  h = 1d0/dble(n)

  call cpu_time(strt)
  !$ strt = omp_get_wtime()

  integ = 0d0

  !$omp parallel default(shared)

  !$omp master
  !$ write(*,*)'Starting with ',omp_get_num_threads(),' threads'
  !$omp end master

  !$omp do private(x)  reduction(+: integ)
  do i = 1, n
     x = dble(i)/dble(n)
     integ = integ + 1d0/(1d0+x**2)*h
  end do
  !$omp end do

  !$omp end parallel

  call cpu_time(stop)
  !$ stop = omp_get_wtime()

  ! Print result and timing
  write(*,*)4*integ, pi, pi-4*integ
  write(*,'(A, ES13.6, A)') 'Finished in ', stop-strt, ' s'

end program compute_pi
$ gfortran -O3 -funroll-loops -fopenmp compute_pi_omp.f90 -o compute_pi_omp
$ export OMP_NUM_THREADS=8
$ ./compute_pi_omp
 Starting with            8  threads
   3.1415926534897518        3.1415926535897931        1.0004130857055316E-010
Finished in  1.816930E+00 s
ThreadsTime (s)Speedup
113.061.0
26.582.0
43.363.9
81.827.2

The speedup is close to ideal up to 8 threads.

The power function

We now parallelize the loop computing the polynomial y=x+x2+⋯+x8y = x + x^2 + \dots + x^8 for n=108n = 10^8 elements that we optimized in the previous lecture:

power_omp.f90
program power
  use omp_lib
  implicit none

  integer, parameter :: n=100000000
  real(kind=8), allocatable :: x(:), y(:)
  real(kind=8) :: t0, t1
  integer :: i, k

  allocate(x(n), y(n))
  call random_number(x)

  !$omp parallel
  !$omp master
  write(*,*)'Starting with ',omp_get_num_threads(),' threads'
  !$omp end master
  !$omp end parallel

  do k=1,4
     t0 = omp_get_wtime()
     !$omp parallel do
     do i=1,n
        y(i)=x(i)*(1+x(i)*(1+x(i)*(1+x(i)*(1+x(i)*(1+x(i)*(1+x(i)*(1+x(i))))))))
     enddo
     !$omp end parallel do
     t1 = omp_get_wtime()
     write(*,*)'pass',k,'time (ms):',1000*(t1-t0),y(k)
  enddo

end program power
$ gfortran -O3 -funroll-loops -fopenmp power_omp.f90 -o power_omp
$ export OMP_NUM_THREADS=8
$ ./power_omp
 Starting with            8  threads
 pass           1 time (ms):   22.678000153973699        7.2436983268545307E-002
 pass           2 time (ms):   13.974000001326203        2.1585180102075436
 pass           3 time (ms):   11.623000027611852       0.49980594530259109
 pass           4 time (ms):   11.748000048100948        2.1502576334309982

As in the previous lecture, the first pass is slower because of page faults, so we report the time of the last pass:

ThreadsTime (ms)Speedup
138.71.0
220.01.9
411.73.3
811.73.3

Note that this is the same performance as the one we obtained in the previous lecture using numba with parallel=True (about 11 ms).

This is disappointing: beyond 4 threads, adding more threads does not help at all. The reason is the memory wall. For each element, the loop reads 8 bytes for x(i) and writes 8 bytes for y(i) (plus 8 more bytes because the cache line of y is first loaded from memory before being written). That is 24 bytes of memory traffic for only 14 floating point operations. With 4 threads, we move 108×2410^8 \times 24 bytes in 11.7 ms, which is about 200 GB/s: this is the maximum bandwidth the cores can get from the main memory on this machine. The cores spend most of their time waiting for the data, and adding more cores only adds more cores waiting for the data.

In contrast, the π\pi example performs only computations on variables that stay in the registers, without accessing the main memory at all, so its performance scales with the number of cores. The ratio between the number of floating point operations and the number of bytes moved to and from the main memory is called the arithmetic intensity. A code with a low arithmetic intensity is memory bandwidth bound, while a code with a high arithmetic intensity is compute bound. Only the latter will scale well with the number of threads on a single node.