Site Tools


openmp

Table of Contents

OpenMP

OpenMP is a shared-memory parallelism API for C, C++, and Fortran. Add a #pragma omp directive before a loop or block to parallelize it across available cores. The compiler handles thread creation and synchronization; if it doesn't support OpenMP, directives are silently ignored and the program runs serially, making debugging easy.

The execution model is fork-join: a single thread forks into a worker team at #pragma omp parallel, they execute concurrently, then join back. Thread count defaults to the number of logical cores, configurable via OMP_NUM_THREADS=N at runtime or omp_set_num_threads(n) in code. Compile with -fopenmp and include <omp.h> for the omp_* runtime functions.

// compile: gcc -O2 -fopenmp -o sum sum.c
// run: OMP_NUM_THREADS=4 ./sum
// description: parallel reduction using a single pragma

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

int main(void) {
    long n = 1000000000L, sum = 0;
    double t = omp_get_wtime();
    #pragma omp parallel for reduction(+:sum)
    for (long i = 0; i < n; i++)
        sum += i;
    printf("sum=%ld  time=%.2fs\n", sum, omp_get_wtime() - t);
    return 0;
}

On a 4-core machine this runs roughly 4× faster with -fopenmp than without. Amdahl's law limits speedup when part of the program is inherently serial; reducing overhead like false sharing and load imbalance matters more than just adding threads.

Concepts

  1. Data sharing
  2. Parallel loops
  3. Collapse
  4. Reduction
  5. Scheduling
  6. SIMD
  7. Tasks
  8. Single
  9. Master
  10. Sections
  11. Barrier
  12. Nowait
  13. Critical sections
  14. Atomic
  15. Flush
  16. False sharing
  17. Thread affinity
  18. Time measurement
  19. Overview
openmp.md · Last modified: