Skip to content

Unit 9 · Shared Memory Parallelisation with OpenMP

3 h contact · 8 h self study Prerequisites: Units 3 and 4 CLO 3 · CLO 4

1. Setting the scene

Scenario: Sixteen cores, one busy

Each SensorGrid server now receives its share of the day's readings through Kafka and stores them in Cassandra. The nightly aggregation on each server still runs on one thread: htop shows one core at 100 % and fifteen idle.

The team does not want to rewrite the program. They want to add a few lines and let the loop use every core.

Guiding questions

  1. How do threads on one machine communicate, and what can go wrong?
  2. What does OpenMP add to a C program, and what does it leave unchanged?
  3. Does creating threads automatically share the work among them?

2. Intended learning outcomes

# Outcome Bloom CLO
ILO 9.1 Contrast the shared and distributed memory models. UNDERSTAND 3
ILO 9.2 Explain the fork and join execution model and the anatomy of an OpenMP directive. UNDERSTAND 4
ILO 9.3 Distinguish a parallel region from worksharing. ANALYSE 4
ILO 9.4 Parallelise loops with for, collapse and reduction, and distribute iterations manually. APPLY 4
ILO 9.5 Explain orphaned directives and region binding. UNDERSTAND 4

3. Why shared memory programming?

Most applications today are parallel. In the 2000s CPU makers ran out of room for boosting clock speeds and turned to multithreading and multicore designs. In HPC, high end CPUs have 36 to 64 cores or more, at lower clock rates: the single core performance of an HPC CPU can be worse than your laptop with turbo boost. Without parallel code, you pay for cores you cannot use.

Two memory models

flowchart LR
    subgraph N1["Node 1"]
      C1["CPU"] --- M1[("Memory")]
    end
    subgraph N2["Node 2"]
      C2["CPU"] --- M2[("Memory")]
    end
    subgraph N3["Node 3"]
      C3["CPU"] --- M3[("Memory")]
    end
    N1 <-->|"interconnect"| N2 <-->|"interconnect"| N3

Multiple computers (nodes), each with its own CPU and memory; memory scales with the number of nodes. One process cannot access another's memory; data is exchanged by explicit message passing with high latency. Typical model: MPI. Common in clusters, supercomputers and clouds.

flowchart TB
    C1["Core 1"] --> RAM[("One shared main memory")]
    C2["Core 2"] --> RAM
    C3["Core 3"] --> RAM
    C4["Core 4"] --> RAM

Several cores share one main memory: IBM Power, Intel Xeon, AMD EPYC, smartphones. All threads can read and write the same memory. OpenMP is designed for this model.

Multithreaded applications

All threads access the shared memory, and threads can also have private data that only the owning thread can access. Threads communicate by reading and writing shared data: thread 1 writes a shared variable, thread 2 reads it.

sequenceDiagram
    participant T1 as Thread 1
    participant S as Shared variable x
    participant T2 as Thread 2
    Note over T1,T2: intended order
    T1->>S: write x = 42
    T2->>S: read x → 42
    Note over T1,T2: without synchronisation, the order may flip
    T2->>S: read x → old value!
    T1->>S: write x = 42

The synchronisation problem and data races

Threads execute asynchronously, so we must ensure reads and writes happen in the correct order. A data race occurs when two or more threads access the same memory location concurrently and at least one access is a write. Without proper synchronisation, behaviour is non deterministic. Unit 11 is devoted to this.

4. Two sources of parallelism

Different operations run in parallel; each thread executes one task, and tasks may spawn sub tasks. Writing a task parallel program means identifying independent computations. Unit 10.

In scientific codes the main source of parallelism is loops. If the iterations are independent, the loop is embarrassingly parallel: each thread works on a portion of the iterations.

A parallel loop, conceptually

unsigned int numbers[] = {1, 2, 3, 4, 5, 6};
unsigned int sum = 0;
const unsigned int quantity = sizeof(numbers) / sizeof(numbers[0]);
for (unsigned int i = 0; i < quantity; ++i)
    sum += numbers[i];

Each iteration reads one element and the order of additions does not matter. Two workers could split it:

unsigned int even_sum = 0;                          /* worker A */
for (unsigned int e = 0; e < quantity; e += 2) even_sum += numbers[e];

unsigned int odd_sum = 0;                           /* worker B */
for (unsigned int o = 1; o < quantity; o += 2) odd_sum += numbers[o];

sum = even_sum + odd_sum;                           /* combine */

The two loops access disjoint indices and share no memory locations, so they can run simultaneously without synchronisation. Real systems generalise this to many threads and cores.

What we need for shared memory programming: a way to create threads, to specify which data is shared or private, to synchronise threads, and to create tasks and loop parallelism. OpenMP provides all of them.

5. OpenMP

Definition

OpenMP is the de facto standard API for shared memory parallel programming, introduced in 1997 (Fortran) and 1998 (C/C++). It consists of compiler directives, runtime library routines and environment variables.

An OpenMP program = a base language (C, C++, Fortran) + annotations with OpenMP directives.

Execution model: fork and join

A program starts with one thread, the master. At a parallel region it forks a team of threads; at the end of the region the workers join back and sleep until the next region. The runtime handles all thread management.

flowchart LR
    S1["serial<br/>master"] --> F{{"fork"}}
    F --> T0["thread 0"]
    F --> T1["thread 1"]
    F --> T2["thread 2"]
    F --> T3["thread 3"]
    T0 & T1 & T2 & T3 --> J{{"join"}}
    J --> S2["serial<br/>master"]

This allows incremental parallelisation: parallelise one hot loop, measure, then the next.

Anatomy of a directive

 #pragma omp   parallel      num_threads(4) private(x)     ← one line
 └─ sentinel ┘ └ construct ┘ └────── clauses ──────────┘
 {
     structured block: one entry at the top, one exit at the bottom
 }

Advantages of directives:

  • they do not modify the serial program: compiled without -fopenmp, the pragmas are ignored and the code runs serially;
  • they can be added incrementally;
  • the compiler replaces them with calls to the OpenMP runtime, so the parallel machinery stays hidden;
  • the code is easier to maintain.

Runtime functions

#include <omp.h>
int omp_get_num_threads(void);   /* threads in the current team (1 outside a parallel region) */
int omp_get_thread_num(void);    /* id of this thread in the team (0 = master)               */
double omp_get_wtime(void);      /* wall clock time for measuring speedup                     */

Hello world

#include <omp.h>
#include <stdio.h>

int main(void) {
    #pragma omp parallel
    {
        int tid = omp_get_thread_num();          /* declared inside: private */
        int nthreads = omp_get_num_threads();
        printf("Hello, I'm thread %d of %d.\n", tid, nthreads);
    }
    return 0;
}
$ gcc -fopenmp -o hello hello.c
$ OMP_NUM_THREADS=4 ./hello
Hello, I'm thread 3 of 4.
Hello, I'm thread 2 of 4.
Hello, I'm thread 1 of 4.
Hello, I'm thread 0 of 4.

The order changes from run to run: threads are scheduled independently. The environment variable OMP_NUM_THREADS sets the team size.

Running on a cluster with SLURM

#!/bin/bash
#SBATCH --time=01:00:00
#SBATCH --ntasks=1
#SBATCH --cpus-per-task=4
#SBATCH --mem-per-cpu=1024
export OMP_NUM_THREADS=$SLURM_CPUS_PER_TASK
module load GCCcore
./your_omp_app

One task (one process) with four CPUs: OpenMP threads live inside a single process.

6. Parallel is not worksharing

The most common beginner mistake

A parallel region creates a team, but each thread executes the whole block redundantly.

#pragma omp parallel
for (int i = 0; i < 1000; i++)      /* every thread runs ALL 1000 iterations */
    count++;
Number of iterations for thread 0: 1000
Number of iterations for thread 1: 1000
Number of iterations for thread 2: 1000
Number of iterations for thread 3: 1000

Worksharing divides the iteration space into chunks and distributes them. With \(n\) iterations and \(p\) threads each thread does about \(n/p\) iterations, so we can expect up to a \(p\) times speedup.

Option 1: distribute iterations by hand

#pragma omp parallel
{
    int tid = omp_get_thread_num();
    int nthreads = omp_get_num_threads();
    int lower = tid * N / nthreads;           /* this thread's share */
    int upper = (tid + 1) * N / nthreads;
    for (int i = lower; i < upper; i++)
        do_work(i);
}
\[ \text{lower}(t) = \left\lfloor \frac{t \cdot n}{p} \right\rfloor, \qquad \text{upper}(t) = \left\lfloor \frac{(t+1) \cdot n}{p} \right\rfloor \]

For \(n = 1000\), \(p = 4\): thread 0 gets \([0, 250)\), thread 1 \([250, 500)\), thread 2 \([500, 750)\), thread 3 \([750, 1000)\).

Option 2: the for directive

#pragma omp parallel
{
    #pragma omp for
    for (int i = 0; i < N; i++)
        do_work(i);
}
Number of iterations for thread 0: 250
Number of iterations for thread 1: 250
Number of iterations for thread 2: 250
Number of iterations for thread 3: 250
gantt
    title Worksharing 1000 iterations over 4 threads
    dateFormat X
    axisFormat %s
    section Thread 0
    i = 0 … 249   :0, 250
    section Thread 1
    i = 250 … 499 :0, 250
    section Thread 2
    i = 500 … 749 :0, 250
    section Thread 3
    i = 750 … 999 :0, 250

The canonical loop form

The for directive requires the loop to be in canonical form:

for (var = start; var  <  end; var += incr)     (also <=, >, >=, ++, --, -=)
  • var must not be modified in the loop body; it is an integer, a pointer or a random access iterator;
  • start, end and incr are loop invariant, so the number of iterations is computable when the loop begins:
\[ n_{\text{iter}} = \left\lceil \frac{\text{end} - \text{start}}{\text{incr}} \right\rceil \]

A while loop, or a loop with break, cannot be workshared this way.

Region binding

A for directive needs a parallel region to bind to. Without one, it binds to the master thread alone:

Number of iterations for thread 0: 1000
Number of iterations for thread 1: 0
Number of iterations for thread 2: 0
Number of iterations for thread 3: 0

The combined directive

#pragma omp parallel          /* two directives ...     */
{
    #pragma omp for
    for (int i = 0; i < n; ++i) do_something(i);
}

#pragma omp parallel for      /* ... or one, equivalent */
for (int i = 0; i < n; ++i) do_something(i);

7. Orphaning

Directives are active in the dynamic scope of a parallel region, not only its lexical scope. A worksharing directive outside the lexical extent of the region is called orphaned; the typical case is a function containing omp for called from inside a parallel region.

void ax(double *x, double a) {
    int done = 0;
    printf("Executing ax by thread %d of %d threads.\n",
           omp_get_thread_num(), omp_get_num_threads());
    #pragma omp for                      /* orphaned: binds to the caller's team, if any */
    for (int i = 0; i < N; i++) { x[i] *= a; done++; }
    printf("Thread with id %d did %d iterations.\n", omp_get_thread_num(), done);
}

int main(void) {
    static double x[N];
    #pragma omp parallel
    ax(x, 2.0);                          /* called inside a parallel region */
    ax(x, 2.0);                          /* called serially */
    return 0;
}
Executing ax by thread 0 of 4 threads.
Executing ax by thread 2 of 4 threads.
Executing ax by thread 1 of 4 threads.
Executing ax by thread 3 of 4 threads.
Thread with id 0 did 250 iterations.
Thread with id 1 did 250 iterations.
Thread with id 2 did 250 iterations.
Thread with id 3 did 250 iterations.
Executing ax by thread 0 of 1 threads.
Thread with id 0 did 1000 iterations.
flowchart TB
    M["main()"] --> PR["#pragma omp parallel<br/>(team of 4)"]
    PR --> A1["ax() · omp for binds to the team<br/>250 iterations per thread"]
    M --> S["serial call"]
    S --> A2["ax() · no team<br/>master does 1000 iterations"]

8. Loop collapsing

When the outer loop is too short to keep all threads busy, merge nested loops into one larger iteration space:

#pragma omp parallel for collapse(2)
for (int i = 0; i < 3; ++i)
    for (int j = 0; j < n; ++j)
        a[i][j] = do_something(i, j);
\[ n_{\text{collapsed}} = 3 \times n, \qquad (i, j) = \left(\left\lfloor \frac{k}{n} \right\rfloor,\; k \bmod n\right) \text{ for } k = 0, \dots, 3n - 1 \]

With 16 threads, the outer loop alone would keep only 3 busy; collapsed, all 16 share \(3n\) iterations. collapse(n) applies only to tightly nested loops: no code between the loop headers.

9. Worked example: the SensorGrid mean

To combine partial results safely, OpenMP offers the reduction clause: each thread gets a private copy, and the copies are combined at the end.

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    const long n = 100000000;                     /* 10^8 readings */
    float *pm25 = malloc(n * sizeof *pm25);
    for (long i = 0; i < n; i++) pm25[i] = (float)(i % 40);

    double sum = 0.0;
    double t0 = omp_get_wtime();
    #pragma omp parallel for reduction(+:sum)
    for (long i = 0; i < n; i++)
        sum += pm25[i];
    double t1 = omp_get_wtime();

    printf("threads=%d mean=%.3f time=%.3f s\n", omp_get_max_threads(), sum / n, t1 - t0);
    free(pm25);
    return 0;
}
flowchart LR
    subgraph T["private partial sums"]
      s0["thread 0: S₀"]
      s1["thread 1: S₁"]
      s2["thread 2: S₂"]
      s3["thread 3: S₃"]
    end
    s0 & s1 & s2 & s3 -->|"combined at the join"| S["sum = S₀ + S₁ + S₂ + S₃"]
\[ \bar{x} = \frac{1}{n}\sum_{t=0}^{p-1} S_t, \qquad S_t = \sum_{i \in \text{chunk}(t)} x_i \]

Measure it yourself

Run with OMP_NUM_THREADS = 1, 2, 4, 8 and fill in \(T(p)\), \(S(p)\) and \(E(p)\). You will find that the speedup flattens early. Why? (Hint: Unit 4. The loop does one addition per 4 bytes loaded; it is memory bound.)

10. Classwork

Predict the output (20 min)

With OMP_NUM_THREADS=3:

  1. #pragma omp parallel around printf("A\n"); How many A's?
  2. #pragma omp parallel for around a loop of 10 iterations that prints i. How many lines? Which thread prints i = 9 with the default static schedule?
  3. A #pragma omp for inside a function called from main without any parallel region. What happens?
  4. collapse(2) on loops of 4 × 5 with 8 threads. How many iterations per thread?
Solutions
  1. Three. 2. Ten lines. With GCC's default static schedule the 10 iterations are split 4, 3, 3: thread 0 gets 0 to 3, thread 1 gets 4 to 6, thread 2 gets 7 to 9, so thread 2 prints i = 9. 3. It binds to the master; one thread executes all iterations. 4. 20 iterations over 8 threads: four threads get 3, four get 2 (with GCC's static schedule).

11. Check your understanding

What is the difference between omp parallel and omp parallel for?

parallel creates a team that executes the block redundantly; parallel for also divides the loop iterations among the team.

Why is the canonical loop form required?

The runtime must compute the number of iterations before the loop starts in order to split them into chunks.

Name the three components of OpenMP.

Compiler directives, runtime library routines, environment variables.

12. Key takeaways

  • OpenMP targets shared memory: threads communicate through shared variables and must be synchronised.
  • Fork and join: one master thread, teams at parallel regions.
  • A parallel region is not worksharing; use omp for (or manual bounds) to divide iterations.
  • Loops must be canonical; collapse enlarges short loop nests; reduction combines partial results safely.
  • Orphaned directives bind dynamically to the enclosing team, or to the master.

Core portfolio task: parallelise the SensorGrid aggregation with OpenMP, report \(T\), \(S\), \(E\) for 1 to 16 threads, and explain the curve with Amdahl's law and memory bandwidth.

Further reading

  • O. Louant, OpenMP training, CISM/CÉCI.
  • OpenMP Architecture Review Board, OpenMP Application Programming Interface, version 5.2.
  • T. Mattson, Y. He, A. Koniges, The OpenMP Common Core, MIT Press, 2019.