Skip to content
VLASIFY™
TutorialHPC, GPU & Linux

OpenMP parallel programming for scientific codes

Updated · Scientifically reviewed by Dinkar Mishra, PhD on

Short answer

OpenMP parallelises code across the cores of one node using compiler directives. Add #pragma omp parallel for before an independent loop, use a reduction clause for sums, compile with -fopenmp, and set OMP_NUM_THREADS. Correctness depends on avoiding race conditions (shared variables written by several threads); performance depends on enough work per thread, good scheduling, and pinning threads to cores (OMP_PROC_BIND, OMP_PLACES) with NUMA-aware first-touch data placement.

Who this is for

Scientists and engineers who want to speed up C, C++ or Fortran simulation codes on multi-core workstations and cluster nodes.

Software

GCC / Clang / Intel oneAPI with OpenMP 4.5+ support

Prerequisites

  • A C/C++ compiler with OpenMP support. GCC: gcc -fopenmp. Clang may need libomp installed.
  • A loop-heavy program whose hot loop you have identified, ideally with a profiler; see how to optimize HPC simulations.

Step 1: parallelise an independent loop

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

int main(void) {
    const long n = 50000000;
    double *a = malloc(n * sizeof(double));
    double *b = malloc(n * sizeof(double));

    #pragma omp parallel for
    for (long i = 0; i < n; i++) {      /* first touch: each thread initialises its own part */
        a[i] = 0.5 * i;
        b[i] = 2.0;
    }

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

    printf("threads=%d  sum=%.6e  time=%.3f s\n", omp_get_max_threads(), sum, t1 - t0);
    free(a);
    free(b);
    return 0;
}
gcc -O2 -fopenmp dot.c -o dot
for t in 1 2 4 8; do OMP_NUM_THREADS=$t ./dot; done

Without reduction(+:sum), all threads would update sum at the same time: a race condition that silently gives wrong answers.

Step 2: avoid race conditions

Ask for every variable: is it written inside the loop, and by whom?

  • Loop-local temporaries: declare them inside the loop body, or mark them private.
  • Accumulations: use reduction(+:x), or reduction(max:x) for maxima.
  • Scattered updates to shared arrays (for example particle-to-grid deposition in PIC): conflicts are possible. Use #pragma omp atomic, per-thread private grids followed by a reduction, or colouring and sorting so that threads never write the same cell.

Step 3: scheduling

#pragma omp parallel for schedule(dynamic, 64)
for (long i = 0; i < n; i++) work(i);   /* when iterations have very different costs */

schedule(static) (the usual default) has the lowest overhead for uniform work. dynamic or guided balance uneven work, such as cells with very different particle counts.

Step 4: pin threads and respect NUMA

export OMP_NUM_THREADS=32
export OMP_PROC_BIND=close     # keep threads near each other
export OMP_PLACES=cores        # one thread per physical core
./simulation

On multi-socket servers, memory is attached to a socket (a NUMA domain). Initialising arrays in a parallel loop with the same schedule as the compute loop (“first touch”) places each page near the thread that uses it.

Verify

  • Correctness: the result with 1 thread and with N threads should agree, up to floating-point summation order for reductions. Run with several thread counts and compare.
  • Race detection: compile with -fsanitize=thread (GCC/Clang ThreadSanitizer) on a small case to catch data races.
  • Scaling: time 1, 2, 4, … threads. Memory-bound loops such as the dot product stop scaling once memory bandwidth saturates, often well before all cores are used. That is expected; see strong vs weak scaling.

Troubleshooting

  • Results change between runs: race condition. Check shared variables, or use ThreadSanitizer.
  • No speedup: check OMP_NUM_THREADS, whether you compiled with -fopenmp, and whether a Slurm job requested --cpus-per-task. Without it, all threads share one core.
  • Slower with more threads: false sharing, oversubscription (MPI ranks × threads exceeding cores), or poor NUMA placement.

Assumptions and limitations

  • Examples use C. The directives are equivalent in C++ and Fortran (!$omp parallel do).
  • Achievable speedup is limited by memory bandwidth for many scientific kernels. More threads do not raise bandwidth.
  • GPU offload with OpenMP is mentioned only briefly. Compiler support and performance vary widely.

Frequently asked questions

How many threads should I use?+

Usually one thread per physical core, not per hardware thread (hyper-threading rarely helps memory-bound simulation codes). Under Slurm, set OMP_NUM_THREADS=$SLURM_CPUS_PER_TASK so you use exactly what you requested.

Why is my OpenMP code slower than the serial version?+

Common reasons: too little work per loop (thread start-up overhead dominates), false sharing (threads writing to neighbouring memory), a critical section or atomic inside a hot loop, or threads moving between cores and NUMA domains. Profile and fix the hottest loop first.

Can OpenMP use GPUs?+

Yes. OpenMP 4.5 and later include target offload directives (#pragma omp target teams distribute parallel for) supported by recent GCC, Clang, NVIDIA HPC SDK and AMD/Intel compilers. Performance depends heavily on the compiler and on minimising data transfers.

Should I use OpenMP or MPI?+

OpenMP is simpler for shared memory within one node. MPI is needed to use multiple nodes. Many simulation codes use MPI between nodes and OpenMP within each node (hybrid parallelism).

References

  1. OpenMP API specifications · OpenMP Architecture Review Board
  2. OpenMP: environment variables (OMP_PROC_BIND, OMP_PLACES) · OpenMP 5.0 specification
  3. GCC libgomp manual · GNU

Want this set up and verified for you?

We install, configure and validate scientific software on your workstation, cluster or cloud, and train your team to run it.

Services listed on this page are available today. Products marked “early access” or “in development” on our platform page are not yet generally available.

Spotted an error or an outdated command? Tell us. We correct verified issues promptly.

Related guides

How Vlasify can help

Get a Quote