Skip to content
systemcoding.dev
Concurrency

The Complete Guide to Parallel Programming with OpenMP

Learn OpenMP in C from the first parallel loop to tasks, SIMD, thread binding and GPU offload, with worked programs, exact output and common mistakes.

29 min read
Summarize in AI
Flat illustration of parallel threads meeting at a mutex, with the C, C++ and Go logos.

OpenMP is the lowest-effort way to use every core of a machine from C, C++ or Fortran. You add a directive above a loop, rebuild with one flag, and the compiler turns the loop into work that a pool of threads shares. The same source still builds and runs as an ordinary serial program when the flag is missing. That short path is also why OpenMP code goes wrong so often: the directive is a promise from you to the compiler that the iterations are independent, and the compiler does not check it. This guide teaches the whole path in C with GCC 14 and Clang 19 on Linux, using OpenMP 4.5 semantics and flagging the 5.x features as they appear. It starts with the fork-join model, then covers parallel loops, data scoping, reductions, schedules, synchronization, tasks, SIMD, thread placement and offloading to a GPU, and it ends with how to test, measure and decide when OpenMP is the wrong tool. Every program is written to be complete and is followed by its exact output.

The claim to remember is this: an OpenMP loop is correct when no iteration writes anything another iteration reads or writes, and fast when each thread gets about the same amount of work and touches its own memory. Almost every section below is a way to check the first half or reach the second.

What OpenMP is and where it fits

OpenMP is a specification, maintained by the OpenMP Architecture Review Board, with three parts: compiler directives (#pragma omp ... in C and C++, !$omp in Fortran), a small runtime library (<omp.h>) and environment variables. A compiler that supports it, such as GCC with -fopenmp or Clang with -fopenmp, translates directives into calls to its OpenMP runtime, libgomp for GCC and libomp for LLVM. The model is shared memory: all threads see the same address space, so there is no data to send between them, and also nothing that stops them from corrupting each other's data.

That puts OpenMP in a specific place. It is not a way to distribute work across machines, which is MPI's job; the two combine, with OpenMP inside each node. It is not an asynchronous I/O framework. It is a way to speed up compute-heavy loops and recursive algorithms on a single machine with multiple cores, and since version 4.0 to offload them to accelerators. Compared with the alternatives in the same space, it asks for the least code. Rayon in Rust and the C++17 parallel algorithms give you library calls instead of pragmas and, in Rust's case, a compiler that rejects the data races; oneTBB gives you more control over scheduling and containers; Go has goroutines for concurrency that is not compute-bound. The section on boundaries at the end says when to pick each.

The fork-join model

An OpenMP program starts as one thread, the primary thread. When it reaches a parallel directive it forks a team of threads, all of which execute the following block. At the end of the block there is an implicit barrier, the team joins, and only the primary thread continues. That cycle can repeat any number of times.

fork-join.cc
#include <stdio.h>
#include <omp.h>

int main(void) {
    printf("before: %d thread(s)\n", omp_get_num_threads());

    #pragma omp parallel num_threads(4)
    {
        #pragma omp single
        printf("inside: %d thread(s)\n", omp_get_num_threads());
    }

    printf("after: %d thread(s)\n", omp_get_num_threads());
    return 0;
}
Text
before: 1 thread(s)
inside: 4 thread(s)
after: 1 thread(s)

The single directive makes exactly one thread of the team print, so the output is three lines instead of six. The three numbers are the model in miniature: one thread, a team of four, one thread again. Two costs follow from it, and both recur throughout this guide. Forking and joining take time, so a parallel region must contain enough work to repay them. And the barrier at the end means a region is as slow as its slowest thread.

Threads in a team are numbered from 0, and a program can ask which one it is.

thread-ids.cc
#include <stdio.h>
#include <omp.h>

int main(void) {
    int ids[4];

    #pragma omp parallel num_threads(4)
    {
        ids[omp_get_thread_num()] = omp_get_thread_num() * 10;
    }

    for (int i = 0; i < 4; i++) printf("slot %d = %d\n", i, ids[i]);
    return 0;
}
Text
slot 0 = 0
slot 1 = 10
slot 2 = 20
slot 3 = 30

Each thread writes its own slot of the shared array, so there is no conflict, and the printing loop runs after the join, in order. Printing from inside the region would work too but would come out in an arbitrary order that changes between runs; collect results into data and print after the join when you want stable output.

Build and run

Everything in this guide builds with the same command shape. The flag has two jobs: it enables the pragmas at compile time and links the runtime at link time.

Shell
gcc -fopenmp -O2 -Wall -Werror=unknown-pragmas prog.c -o prog
clang -fopenmp -O2 -Wall prog.c -o prog

Without -fopenmp the pragmas are comments and the program is correct and serial, which is exactly how you should first check any change: build it both ways and compare the output. The macro _OPENMP is defined only when OpenMP is on, and its value is the year and month of the specification the compiler implements, 201511 for OpenMP 4.5. The thread count comes from OMP_NUM_THREADS, from omp_set_num_threads(), or from a num_threads clause, in increasing order of priority. GCC 14 reports 201511 and Clang 19 reports 201811; both support useful subsets of 5.x, and the GCC OpenMP status page and the LLVM documentation say which. The full build troubleshooting, including the errors you meet when you forget to link the runtime and how to confirm that your pragmas took effect, is in compiling and running OpenMP programs with GCC and Clang.

Two habits save most of the pain. First, build with -Wall and -Werror=unknown-pragmas, so that a misspelled #pragma omp paralel for stops the build instead of silently running on one core. Second, print omp_get_max_threads() or set OMP_DISPLAY_ENV=true the first time you run on a new machine, since a container or a leftover OMP_NUM_THREADS=1 is the usual reason a parallel program does not speed up.

Parallel loops and the independence rule

The workhorse directive is parallel for. It forks a team and divides the iterations of the next loop among them.

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

#define N 8

int main(void) {
    int a[N];

    #pragma omp parallel for
    for (int i = 0; i < N; i++) {
        a[i] = i * i;
    }

    for (int i = 0; i < N; i++) printf("a[%d] = %d\n", i, a[i]);
    return 0;
}
Text
a[0] = 0
a[1] = 1
a[2] = 4
a[3] = 9
a[4] = 16
a[5] = 25
a[6] = 36
a[7] = 49

Each iteration writes only its own element, so the iterations are independent and the output is the same on every run. The directive requires the loop to be in canonical form: an integer or pointer loop variable, a test against a loop-invariant bound, and a fixed increment, so that the trip count is known when the loop starts. A break, a return out of the loop, or a modified loop counter inside the body is not allowed.

The independence rule is the part the compiler cannot check, and a loop that breaks it compiles and runs. The recurrence a[i] = a[i-1] + 1 reads what the previous iteration writes. The accumulation sum += x[i] has every iteration writing the same variable, which is a data race. Both give a wrong answer that differs from run to run. The rule for deciding in practice is to ask, for every variable the loop body touches, whether two different iterations could access the same location with at least one of them writing. If the answer is yes, the variable needs a different treatment from the sections below, or the loop needs restructuring. The full treatment of the loop pragma, including parallel versus for as separate directives and the small-loop problem, is in parallelizing a loop with a pragma.

The same pragma can be guarded at run time by an if clause, so tiny inputs run serially and skip the fork-join cost.

if-clause.cc
#include <stdio.h>
#include <omp.h>

static void scale(double *x, int n, double k) {
    #pragma omp parallel for if(n > 10000)
    for (int i = 0; i < n; i++) x[i] *= k;
}

int main(void) {
    double v[4] = {1.0, 2.0, 3.0, 4.0};
    scale(v, 4, 2.0);
    printf("%.1f %.1f %.1f %.1f\n", v[0], v[1], v[2], v[3]);
    return 0;
}
Text
2.0 4.0 6.0 8.0

The threshold of 10,000 is a placeholder. The right value depends on what the loop does and on the machine, and you find it by measuring. A loop of eight multiplications is always faster serial; a loop of ten million is almost always worth splitting, unless it is limited by memory bandwidth, in which case extra threads add little.

Who owns each variable: data scoping

When the team starts, each variable used in the region is either shared, one copy that all threads see, or private, one copy per thread. Variables declared before the region are shared by default, which is the root of the most common bug in OpenMP code: a scratch variable declared outside the loop and written inside it is shared, so threads overwrite each other's temporaries.

shared-temp.cc
#include <stdio.h>

#define N 6

int main(void) {
    double out[N];

    #pragma omp parallel for
    for (int i = 0; i < N; i++) {
        double t = i * 2.0;          /* declared inside: private to each iteration */
        out[i] = t + 1.0;
    }

    printf("out[5] = %.1f\n", out[5]);
    return 0;
}
Text
out[5] = 11.0

Declaring the temporary inside the loop body makes it private by construction, and that is the cleanest fix. When the declaration must stay outside, the clauses decide: private(x) gives each thread an uninitialized copy, firstprivate(x) gives each a copy initialized from the original, lastprivate(x) copies the value from the logically last iteration back out, shared(x) keeps one copy, and reduction combines per-thread copies at the end. The surprise is that private does not copy the value in.

private-vs-first.cc
#include <stdio.h>

int main(void) {
    int base = 100;
    int out[4];

    #pragma omp parallel for firstprivate(base)
    for (int i = 0; i < 4; i++) {
        out[i] = base + i;
    }

    for (int i = 0; i < 4; i++) printf("out[%d] = %d\n", i, out[i]);
    return 0;
}
Text
out[0] = 100
out[1] = 101
out[2] = 102
out[3] = 103

With private(base) instead, each thread's copy would start uninitialized and the sums would be garbage. The habit that turns this whole category of bug into a compile error is default(none): it removes the implicit sharing rules, so the compiler refuses any variable you have not classified.

default-none.cc
#include <stdio.h>

int main(void) {
    int n = 5;
    double scale = 0.5;
    double in[5] = {2.0, 4.0, 6.0, 8.0, 10.0};
    double out[5];

    #pragma omp parallel for default(none) shared(n, in, out) firstprivate(scale)
    for (int i = 0; i < n; i++) {
        out[i] = in[i] * scale;
    }

    for (int i = 0; i < n; i++) printf("%.1f ", out[i]);
    printf("\n");
    return 0;
}
Text
1.0 2.0 3.0 4.0 

Leave scale out of the clauses and GCC stops with an error saying it is not specified in the enclosing parallel. The error is the point: the question "did we decide how this variable is shared" became a build failure. Put default(none) on every construct. The longer treatment, with lastprivate, the pitfalls of private pointers and a rule for choosing a clause for each variable, is in scoping variables with private, firstprivate and default(none).

Combining results: reduction

An accumulation across iterations is the case where every iteration writes the same variable, and the reduction clause is the intended answer. Each thread accumulates into its own private copy, initialized to the identity of the operator, and the runtime combines the copies at the end of the loop.

sum-reduction.cc
#include <stdio.h>

int main(void) {
    long sum = 0;

    #pragma omp parallel for reduction(+:sum)
    for (int i = 1; i <= 100000; i++) {
        sum += i;
    }

    printf("sum = %ld\n", sum);
    return 0;
}
Text
sum = 5000050000

The same loop without the clause has a data race on sum and prints a different wrong number on each run. The built-in operators are +, -, *, &, |, ^, &&, ||, min and max, and since OpenMP 4.5 a reduction item can be an array section, which gives a histogram without a lock. The original value of the variable takes part in the final combination, so initialize it deliberately.

histogram.cc
#include <stdio.h>

#define BINS 4

int main(void) {
    int scores[] = {12, 47, 88, 63, 5, 91, 34, 72, 58, 20, 99, 41};
    int n = 12;
    int hist[BINS] = {0, 0, 0, 0};

    #pragma omp parallel for reduction(+:hist[:BINS])
    for (int i = 0; i < n; i++) {
        int bin = scores[i] / 25;
        if (bin > BINS - 1) bin = BINS - 1;
        hist[bin]++;
    }

    for (int b = 0; b < BINS; b++) printf("bin %d: %d\n", b, hist[b]);
    return 0;
}
Text
bin 0: 3
bin 1: 3
bin 2: 3
bin 3: 3

One caveat deserves its own sentence: floating-point addition is not associative, so a parallel floating-point reduction can differ from the serial result in the last bits, and from one thread count to another, because the grouping of the additions changes. Compare such results with a tolerance. Details, including declare reduction for your own types, are in combining results with the reduction clause.

Balancing the work: schedules

A parallel loop is only as fast as its slowest thread. If iteration cost is uniform, giving each thread an equal block is ideal. If it is not, one thread finishes early and idles at the barrier. The schedule clause chooses how iterations are handed out. This program records which thread ran each iteration under three static variants.

schedule-static.cc
#include <stdio.h>
#include <omp.h>

#define N 12

static void show(const char *label, const int *owner) {
    printf("%-10s", label);
    for (int i = 0; i < N; i++) printf("%d ", owner[i]);
    printf("\n");
}

int main(void) {
    int owner[N];

    #pragma omp parallel for num_threads(4) schedule(static)
    for (int i = 0; i < N; i++) owner[i] = omp_get_thread_num();
    show("static", owner);

    #pragma omp parallel for num_threads(4) schedule(static, 1)
    for (int i = 0; i < N; i++) owner[i] = omp_get_thread_num();
    show("static,1", owner);

    #pragma omp parallel for num_threads(4) schedule(static, 2)
    for (int i = 0; i < N; i++) owner[i] = omp_get_thread_num();
    show("static,2", owner);
    return 0;
}
Text
static    0 0 0 1 1 1 2 2 2 3 3 3 
static,1  0 1 2 3 0 1 2 3 0 1 2 3 
static,2  0 0 1 1 2 2 3 3 0 0 1 1 

Static scheduling decides the assignment before the loop runs, so it has no run-time overhead and keeps each iteration on the same thread from one run of the loop to the next, which helps the cache. It fails when iteration cost varies. dynamic, chunk keeps a queue of chunks that threads claim as they finish, which balances any distribution at the price of a synchronized claim per chunk, and guided starts with large chunks and shrinks them toward the end. The rule that picks between them is the shape of the cost: equal cost uses static; a smooth slope uses static with a small chunk; random, data-dependent cost uses dynamic with a chunk large enough to repay the claim; mild unevenness over many iterations uses guided. Use schedule(runtime) and the OMP_SCHEDULE variable to compare them without recompiling. The worked comparison, with a triangular workload that makes static visibly lopsided, is in choosing OpenMP schedules.

A complete example where dynamic scheduling is the right call is counting primes by trial division. A number near the bound takes far more work to test than a small one, and composites are rejected early while primes need every divisor tried, so the cost per iteration is wildly uneven.

primes.cc
#include <stdio.h>

static int is_prime(int k) {
    if (k < 2) return 0;
    for (int d = 2; (long)d * d <= k; d++) {
        if (k % d == 0) return 0;
    }
    return 1;
}

int main(void) {
    int count = 0;

    #pragma omp parallel for schedule(dynamic, 256) reduction(+:count)
    for (int k = 2; k < 100000; k++) {
        count += is_prime(k);
    }

    printf("primes below 100000: %d\n", count);
    return 0;
}
Text
primes below 100000: 9592

There are 9,592 primes below 100,000, the same answer under every schedule, which is the property to rely on: a schedule changes who runs which iteration, never what the loop computes. If a schedule changes your answer, the loop was never independent.

Nested loops and a complete matrix product

For nested loops there are two questions: which loop to parallelize, and whether the outer loop has enough iterations to occupy all the threads. The collapse(n) clause merges n perfectly nested loops into one iteration space. The classic example is a matrix product, where the two outer loops are independent and the inner loop is a dot product.

matmul.cc
#include <stdio.h>

#define N 4

int main(void) {
    int A[N][N], B[N][N], C[N][N];

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            A[i][j] = i + j;
            B[i][j] = i * j + 1;
        }
    }

    #pragma omp parallel for collapse(2) default(none) shared(A, B, C)
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            int sum = 0;
            for (int k = 0; k < N; k++) sum += A[i][k] * B[k][j];
            C[i][j] = sum;
        }
    }

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) printf("%4d", C[i][j]);
        printf("\n");
    }
    return 0;
}
Text
   6  20  34  48
  10  30  50  70
  14  40  66  92
  18  50  82 114

Each C[i][j] is written by exactly one iteration of the collapsed loop, and the accumulator sum is declared inside it, so it is private. The inner k loop stays serial, as it should: parallelizing it would need a reduction per element and a tiny amount of work per thread. For a real matrix you would also care about memory access: in C the last index is contiguous, so an inner loop that walks B[k][j] down a column strides through memory. The standard remedy is blocking or transposing B, and it is the first thing to try when a matrix kernel scales poorly. The sample is small so the output is checkable by hand: C[0][0] is the sum over k of (0 + k) * (k * 0 + 1), which is 0 + 1 + 2 + 3 = 6.

Dividing work that is not a loop

Not all parallel work is an index range. A few directives cover the rest, and they are about who runs a block and when threads meet.

single runs a block on exactly one thread, whichever arrives first, with an implicit barrier after it. master (renamed masked in 5.1) runs a block on the primary thread only, with no barrier. sections assigns each section block to a different thread.

sections.cc
#include <stdio.h>

int main(void) {
    long a = 0, b = 1;

    #pragma omp parallel sections default(none) shared(a, b)
    {
        #pragma omp section
        for (int i = 1; i <= 100; i++) a += i;

        #pragma omp section
        for (int j = 1; j <= 5; j++) b *= j;
    }

    printf("a = %ld, b = %ld\n", a, b);
    return 0;
}
Text
a = 5050, b = 120

Each section writes its own variable, so there is no race. sections fits a small fixed set of unlike jobs; for anything that scales with the data, use a loop or tasks. A barrier makes every thread wait for the rest, and most constructs already end in one. The nowait clause removes it:

nowait.cc
#include <stdio.h>

#define N 8

int main(void) {
    int a[N], b[N];

    #pragma omp parallel
    {
        #pragma omp for nowait
        for (int i = 0; i < N; i++) a[i] = i;

        #pragma omp for
        for (int i = 0; i < N; i++) b[i] = 2 * i;
    }

    printf("a[7] = %d, b[7] = %d\n", a[7], b[7]);
    return 0;
}
Text
a[7] = 7, b[7] = 14

This is safe because the second loop never reads a. If it read a[i-1], the nowait would let a thread race ahead and read a slot that no thread had written yet. Remove a barrier only when you can state why nothing after it depends on what the construct wrote.

Protecting shared updates: critical, atomic, locks

Sometimes shared mutation is unavoidable. OpenMP offers three tools, in increasing power and cost. atomic makes one simple update indivisible, usually with a hardware instruction. critical serializes a block, with one lock per name across the whole program. Explicit locks (omp_set_lock) are the most flexible and the easiest to get wrong.

atomic-vs-critical.cc
#include <stdio.h>

int main(void) {
    long hits = 0;
    int max_seen = 0;

    #pragma omp parallel for
    for (int i = 0; i < 1000; i++) {
        #pragma omp atomic
        hits++;

        int v = (i * 37) % 1000;
        #pragma omp critical(maxupdate)
        {
            if (v > max_seen) max_seen = v;
        }
    }

    printf("hits = %ld, max = %d\n", hits, max_seen);
    return 0;
}
Text
hits = 1000, max = 999

The counter is a single update, so atomic fits. The maximum needs a compare and a conditional store, a compound operation atomic cannot express, so it goes in a named critical section. Naming matters: two unnamed critical blocks share one lock even if they protect unrelated data. And i * 37 % 1000 takes every value from 0 to 999 as i does, because 37 and 1000 share no factor, so the maximum is 999. In real code the max update would be a reduction(max:max_seen), which is faster than either tool because it takes no lock in the loop. The order of preference for a shared update is: remove the sharing, use reduction, use atomic, use critical, use an explicit lock.

These tools fix data races but not logic races. Two separate critical sections guarding one decision are still a check-then-act bug, a topic taken up in the data-race half of this series.

Tasks for work that is not a range

Recursion, tree walks and irregular work have no index range to split. Tasks handle them. A task directive packages the next statement as a unit of work that any thread in the team may run later, and taskwait waits for the children. The region starts with parallel to create the threads and single so only one thread starts the recursion.

fib-tasks.cc
#include <stdio.h>

static long fib_serial(int n) {
    return n < 2 ? n : fib_serial(n - 1) + fib_serial(n - 2);
}

static long fib(int n) {
    if (n < 20) return fib_serial(n);

    long x, y;

    #pragma omp task shared(x)
    x = fib(n - 1);

    #pragma omp task shared(y)
    y = fib(n - 2);

    #pragma omp taskwait
    return x + y;
}

int main(void) {
    long result = 0;

    #pragma omp parallel
    {
        #pragma omp single
        result = fib(30);
    }

    printf("fib(30) = %ld\n", result);
    return 0;
}
Text
fib(30) = 832040

The line if (n < 20) return fib_serial(n); is the most important line in the program. Creating a task costs far more than a function call, so a task per call spends nearly all its time on bookkeeping and the program runs slower than serial. Below some size, the work must run inline. The cutoff of 20 is a tuning value you set by measuring. final(expr) does the same job with a clause, and for recursion it is the right clause, since if(expr) makes only the one task undeferred and its children still go to the queue. The shared variables x and y live on the creating call's stack, and taskwait is what guarantees that stack frame is still alive when the tasks finish. A task reading a stack variable from a function that has already returned is a use-after-return. The full treatment, with a tree walk, a loop that generates tasks and the list of ways tasks go wrong, is in OpenMP tasks for recursive parallelism.

When tasks have dependencies, the depend clause (OpenMP 4.0) expresses them without a taskwait, as in #pragma omp task depend(in: a) depend(out: b). The runtime then orders tasks by the data they read and write, which is how you build a pipeline or a blocked factorization without barriers. For counted loops that you want balanced dynamically, taskloop (OpenMP 4.5) is simpler than creating tasks by hand.

Vectorization with simd

A single core can operate on several array elements per instruction using SIMD registers. The compiler often vectorizes simple loops by itself at -O3, and when it cannot prove that iterations are independent it holds back. The simd directive is your promise that they are.

simd.cc
#include <stdio.h>

#define N 8

int main(void) {
    float x[N], y[N];
    float a = 2.0f;

    for (int i = 0; i < N; i++) {
        x[i] = (float)i;
        y[i] = 1.0f;
    }

    #pragma omp simd
    for (int i = 0; i < N; i++) {
        y[i] = a * x[i] + y[i];
    }

    printf("y[7] = %.1f\n", y[7]);
    return 0;
}
Text
y[7] = 15.0

parallel for simd combines both levels: threads split the range, and each thread vectorizes its share. The directive does not check the claim, so a loop with a dependence at a distance shorter than the vector width gives wrong answers. The safelen(n) clause states the largest distance that is safe. The practical advice is to let the compiler vectorize first, read its report (-fopt-info-vec on GCC, -Rpass=loop-vectorize on Clang), and add simd only where the report says it declined and you can prove independence. Forcing vectorization with omp simd covers that workflow.

Thread placement and memory

On a laptop all cores are alike. On a multi-socket server they are not: each socket has its own memory controller, and a thread that reads memory attached to the other socket pays extra latency. Two things govern whether your threads and your data end up near each other.

The first is thread binding. By default the operating system may move threads between cores at will. OMP_PLACES names the hardware locations (threads, cores, sockets) and OMP_PROC_BIND says how the team is spread over them: close packs threads onto adjacent places, which suits threads that share data and cache, and spread distributes them evenly, which suits bandwidth-bound loops that should use every memory controller. Setting both and confirming the result with OMP_DISPLAY_AFFINITY=true is the first step of any benchmark on such a machine.

The second is first touch. Linux places a page in the memory attached to the CPU that first writes it. A serial initialization loop puts every page on the primary thread's node, and the bound worker threads on the other socket then read remote memory for the whole run. The fix is to initialize in parallel with the same schedule as the compute loop.

first-touch.cc
#include <stdio.h>
#include <stdlib.h>

#define N (1L << 24)

int main(void) {
    double *a = malloc(N * sizeof *a);
    double *b = malloc(N * sizeof *b);

    #pragma omp parallel for schedule(static)
    for (long i = 0; i < N; i++) {
        a[i] = 1.0;
        b[i] = 2.0;
    }

    double dot = 0.0;
    #pragma omp parallel for schedule(static) reduction(+:dot)
    for (long i = 0; i < N; i++) dot += a[i] * b[i];

    printf("dot = %.1f\n", dot);
    free(a);
    free(b);
    return 0;
}
Text
dot = 33554432.0

The result is identical whatever the placement, 2^24 products of 2.0, so correctness is unaffected; only the speed on a multi-socket machine changes. Binding and first touch, with the display variables and the close-versus-spread decision table, are in binding OpenMP threads with OMP_PROC_BIND and OMP_PLACES.

Offloading to a GPU

Since OpenMP 4.0 the same directive model can run a loop on an accelerator. The target directive moves execution to a device, teams distribute parallel for spreads iterations across the device's teams and threads, and map clauses say which arrays to copy.

saxpy-target.cc
#include <stdio.h>

#define N 1024

int main(void) {
    float x[N], y[N];
    float a = 2.0f;

    for (int i = 0; i < N; i++) {
        x[i] = (float)i;
        y[i] = 1.0f;
    }

    #pragma omp target teams distribute parallel for \
        map(to: x[0:N]) map(tofrom: y[0:N])
    for (int i = 0; i < N; i++) {
        y[i] = a * x[i] + y[i];
    }

    printf("y[1023] = %.1f\n", y[N - 1]);
    return 0;
}
Text
y[1023] = 2047.0

The program prints the same value whether it ran on a GPU or fell back to the host, which is both a feature and a trap: without a device, or with a compiler built without offload support, the region silently runs on the CPU. Check with omp_is_initial_device() or set OMP_TARGET_OFFLOAD=MANDATORY in benchmarks. Offload pays only when the arithmetic per transferred byte is high, since each map is a copy over the bus; a bare SAXPY is a teaching example, not an offload candidate. The build lines for GCC and Clang, target data to keep arrays resident across kernels and the list of pitfalls are in offloading work to GPUs with OpenMP target.

Testing a parallel program

A parallel loop that returns the right answer once has proven little. The failures that matter depend on timing, so the tests have to vary it.

Compare to serial, always. Build the program without -fopenmp and diff its output against the parallel build over many inputs. Integer results must match exactly. Floating-point results must match within a tolerance that reflects reordered summation, and you should choose that tolerance on purpose, not by loosening it until the test passes.

Vary the thread count. Run with 1, 2, 3, 7 and 64 threads. A race often hides at two threads and appears at eight, and a bug that depends on the thread count dividing the iteration count appears only at odd values.

Run a race detector. ThreadSanitizer finds unsynchronized access, though OpenMP programs need a runtime that the tool understands: LLVM's Archer pairs it with the OpenMP runtime so synchronization inside the runtime is not misreported. A race detector that does not know the runtime floods you with false positives from the barrier implementation, which is a reason to treat its output with care and not to abandon it. Detecting data races with ThreadSanitizer covers the tool itself.

Check the pragma took effect. Test _OPENMP at build time and omp_get_max_threads() at run time, and build with -Werror=unknown-pragmas. A program that silently stopped being parallel passes every correctness test.

Measuring speedup and finding why it stops

Parallel speedup is measured, never assumed. Time the same job at several thread counts and compute speedup against the single-thread run of the parallel build, not against an unrelated serial build. omp_get_wtime() returns wall-clock seconds as a double.

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

int main(void) {
    double t0 = omp_get_wtime();
    long hits = 0;

    #pragma omp parallel for schedule(static) reduction(+:hits)
    for (long i = 0; i < 200000000L; i++) {
        if (i % 3 == 0) hits++;
    }

    double t1 = omp_get_wtime();
    fprintf(stderr, "threads=%d seconds=%.3f\n", omp_get_max_threads(), t1 - t0);
    printf("hits = %ld\n", hits);
    return 0;
}
Text
hits = 66666667

The timing line goes to standard error, so a script can compare the checksum on standard output across runs while collecting times separately. i % 3 == 0 holds for 66,666,667 of the values below 200,000,000. The speedup you measure will fall short of the thread count, and the reason is one of a short list. A serial section caps the speedup at the reciprocal of its fraction, which is Amdahl's law: with 5 percent serial, 20 is the ceiling however many cores you add. Overhead that grows with the thread count, such as barriers and contended locks, makes the loss increase as you add threads; the Karp-Flatt metric separates the two, since it stays constant for a true serial fraction and rises for growing overhead. Load imbalance, false sharing and memory-bandwidth saturation each have their own fingerprint in perf. The theory is in Amdahl's law and Gustafson's law for real programs and the measurement workflow, with perf stat, perf record and perf c2c, is in profiling parallel scalability with perf and OpenMP tools.

False sharing deserves a warning here because it hides in the most innocent code: an array of per-thread counters. Eight long counters occupy 64 bytes, one cache line, so every increment by one thread invalidates the line in the other cores' caches, and the loop gets slower as threads are added. The fix is a local accumulator that is written to the shared array once, or padding each element to its own cache line.

An end-to-end example: numerical integration

A last complete program ties the pieces together: a parallel loop, a reduction, default(none), a schedule and a verified answer. It estimates pi by integrating 4 / (1 + x^2) from 0 to 1 with the midpoint rule.

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

int main(void) {
    const long n = 1000000;
    const double h = 1.0 / (double)n;
    double sum = 0.0;

    #pragma omp parallel for default(none) shared(h) firstprivate(n) \
        schedule(static) reduction(+:sum)
    for (long i = 0; i < n; i++) {
        double x = ((double)i + 0.5) * h;
        sum += 4.0 / (1.0 + x * x);
    }

    printf("pi = %.10f\n", sum * h);
    return 0;
}
Text
pi = 3.1415926536

The midpoint rule with a million intervals is accurate to well beyond ten decimal places, and printing ten places makes the output independent of the summation order: the reordering error of a parallel sum is around the sixteenth digit, far below what %.10f shows. That is the practical way to print a floating-point result from a parallel program you want to compare across runs. The variable h is shared because it is only read; n is firstprivate to show the clause, though shared would do; x is declared inside the loop, so it is private; sum is a reduction.

The mistakes that cost the most time

After the first week with OpenMP, the same handful of mistakes account for most of the lost afternoons. They are worth listing in one place, with the symptom that gives each away.

MistakeSymptomCheck or fix
Forgot -fopenmp, or misspelled the pragmaCorrect output, one core busy_OPENMP test, -Werror=unknown-pragmas, OMP_DISPLAY_ENV=true
Shared scratch variable written in the loopDifferent wrong answer each runDeclare it inside the loop, or private; use default(none)
sum += x with no reductionResult below the true total, varyingreduction(+:sum)
private used where the old value was neededGarbage in the output, a warning about use before setfirstprivate
Loop-carried dependence, such as a[i] = a[i-1] + 1Wrong, but only with more than one threadRestructure, or leave the loop serial
Fork-join inside a hot serial loopSlower than the serial programOne region around the outer loop, with for inside
No cutoff on recursive tasksSlower than serial, huge task countsSerial fallback below a size, or final(expr)
nowait with a later read of the same dataRare wrong resultsRemove nowait or add a barrier
False sharing on per-thread countersSlows down as threads are addedLocal accumulator, or pad to a cache line
Two runtimes in one processSlowdown, oversubscribed coresOne OpenMP runtime per process

Two of these deserve a sentence more. The fork-join mistake appears when a function with a parallel loop is called a million times from a serial outer loop: each call forks and joins, and the overhead dwarfs the loop. Move the parallel outward so one team spans the outer loop, and put omp for on the inner loops. The two-runtimes mistake appears when a library built against LLVM's libomp is linked into a program built against GCC's libgomp: each creates its own thread pool, the pools compete for the same cores, and the symptom is a slowdown that vanishes when you drop one of them.

Environment variables worth knowing

The runtime reads its configuration from environment variables, which lets one binary serve a benchmark, a test and production without recompiling. A short list covers nearly all use.

VariableEffect
OMP_NUM_THREADSDefault team size, unless a num_threads clause overrides it
OMP_SCHEDULEThe schedule used by loops that say schedule(runtime)
OMP_PROC_BIND and OMP_PLACESWhere threads may run: close, spread, and cores, threads or sockets
OMP_WAIT_POLICYWhether waiting threads spin (active) or sleep (passive)
OMP_DISPLAY_ENVPrint the runtime's resolved configuration at startup
OMP_DISPLAY_AFFINITYPrint where each thread is bound (OpenMP 5.0)
OMP_TARGET_OFFLOADMANDATORY makes a missing device an error instead of a silent host fallback
OMP_STACKSIZEStack size of worker threads, raised when deep recursion overflows it

Set OMP_NUM_THREADS from the outside, not in the code. A library that calls omp_set_num_threads(4) takes the decision away from the person who knows how many cores the job has. The same goes for num_threads clauses inside library functions. One more variable matters in containers: a CPU quota from a container runtime does not shrink the number of processors the runtime sees, so a job limited to two CPUs on a sixty-four core host may start sixty-four threads and be throttled. Set OMP_NUM_THREADS to the quota.

Nested parallelism and OpenMP inside libraries

A parallel region inside another parallel region is nested parallelism. By default, nested regions run with a team of one, because oversubscribing the cores usually hurts: if each of eight threads forks eight more, sixty-four threads compete for eight cores. The maximum depth is controlled by OMP_MAX_ACTIVE_LEVELS, and you should raise it only when you can say what each level is for, for example an outer level spread across sockets and an inner level packed within one socket.

The more common situation is a function that contains a parallel loop, called from code that is already parallel. The function behaves correctly, since the nested region collapses to one thread, but it is not parallel at that point. Design libraries so the caller controls the parallelism: provide a serial core function that contains no pragmas and, if useful, a thin wrapper that adds the parallel loop. A library function that forks threads on its own, with a hard-coded count, is a hazard to every program that links it.

When not to use OpenMP

The honest boundary is longer than it looks. OpenMP is the wrong choice in these cases, each with a person behind it.

You need to scale across machines. OpenMP is shared memory on one node. A cluster needs MPI, and the two combine, with one MPI process per node and OpenMP threads inside it.

You write in Rust. The compiler rejects the data races that OpenMP lets through, and Rayon expresses the same loops with par_iter, see parallelizing iterators with Rayon. You write modern C++ and want the standard library to do the work: C++17 parallel algorithms are a function-call interface, and oneTBB gives containers, pipelines and finer control over tasks than OpenMP does. You write Go, where goroutines and the scheduler do the job, and container limits are the thing to tune, see GOMAXPROCS in containers.

Your work is waiting, not computing. A server that spends its time on the network or a disk gains nothing from compute threads. Use an event loop or asynchronous I/O.

The loop has a true dependence. A recurrence, a prefix sum written naively, or a pointer-chasing traversal cannot be split by a directive. Restructure the algorithm first, for example with a parallel prefix scan, or accept the serial section and shrink it.

Your problem is memory-bound. If the loop streams through arrays far larger than the caches, the memory bus is the limit and more threads do not help. Reduce the data moved, with blocking, a smaller data type or fused loops, before adding cores.

You need deterministic bits. A parallel floating-point reduction does not promise the same result across thread counts. If you need bit-identical output, sum in a fixed tree of fixed-size blocks that you control.

The code is small and fast already. A loop that runs in microseconds loses to the cost of the fork. Parallelize the caller, at a coarser level, so one region wraps a lot of work.

For the reference, the OpenMP directives and clauses cheat sheet lists every directive, clause and environment variable with the situation in which not to use it, and the companion topic on finding data races and deadlocks covers the bugs this guide keeps warning about. The official specification and the reference guides on the OpenMP website are the authority when a compiler's behavior is unclear, and GCC's and LLVM's status pages say which parts of each version they implement.

For the authoritative option and behavior details, see the OpenMP specifications and reference guides.

Share

Keep reading

Flat illustration of two options weighed side by side, with the C, C++ and Rust logos.
Performance

Spinlocks vs Mutexes: When Spinning Wins

A spinlock burns a core while it waits and a mutex sleeps. Compare their costs, write a correct C11 spinlock, and see when user-space spinning beats a mutex.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.