Skip to content
systemcoding.dev
Concurrency

Scope Variables in OpenMP With private, firstprivate and default(none)

Decide which OpenMP variables are shared, private, firstprivate or lastprivate, and use default(none) so the compiler forces you to state every choice.

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

Most wrong answers from OpenMP programs are not exotic. They are a variable the author never decided about: a temporary that every thread overwrites, a copy that starts as garbage, a result that vanishes when the loop ends. OpenMP applies default rules to variables you did not mention, and the defaults are right often enough to hide the cases where they are not. The fix is a habit rather than a memory test: write default(none) on every parallel construct, and the compiler stops you at each variable you have not classified. This post uses OpenMP 4.5 and GCC 14, defines the five data-sharing attributes with code that prints what each does, and ends with the rule for choosing. It assumes you already know how to parallelize a loop with a pragma.

The five attributes

A variable in a parallel region is either one copy that all threads see, or one copy per thread. The clauses decide which, and what the per-thread copies start and end as.

ClauseCopiesStarts asAfter the construct
shared(x)one, all threadsthe current valuewhatever the threads wrote
private(x)one per threaduninitializeddiscarded
firstprivate(x)one per threadcopy of the originaldiscarded
lastprivate(x)one per threaduninitializedvalue from the last iteration
reduction(op:x)one per threadthe operator's identitycombined into the original

Each attribute exists for a reason you can name. shared is for arrays and structures that threads read, or write at disjoint places. private is scratch space. firstprivate is scratch space that needs an initial value. lastprivate carries one value out of a loop. reduction carries a combination out of a loop, and combining results with the reduction clause covers it.

private starts uninitialized

The commonest surprise is that private(x) does not copy anything in. The private copy exists, and it holds whatever bytes were in that memory.

private-bug.cc
#include <stdio.h>

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

    #pragma omp parallel for private(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;
}

base inside the loop is a new, uninitialized variable, not the 100 you set outside. Reading it is undefined behavior, so the output might be anything.

Text
out[0] = 21845
out[1] = 21846
out[2] = 21847
out[3] = 21848

Those numbers are one possible garbage value, not a prediction. GCC with -Wall warns about this one: 'base' is used uninitialized. The fix is firstprivate, which copies the original value into each thread's private copy at entry.

firstprivate-fix.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

Here base is only read, so shared(base) gives the same result with no copy. firstprivate earns its keep when each thread modifies its copy, for example a running offset that each thread advances locally.

shared and the shared-by-default trap

Variables declared before the construct are shared unless you say otherwise. That is the opposite of what most people assume about "locals". This is the bug from earlier in the series, in its pure form.

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

int main(void) {
    double t;
    double out[6];

    #pragma omp parallel for
    for (int i = 0; i < 6; i++) {
        t = i * 2.0;
        out[i] = t + 1.0;
    }

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

t is shared, so between one thread's t = i * 2.0 and its out[i] = t + 1.0 another thread can overwrite t. On a quiet machine you get the right answer by luck, 11.0 here, and the bug waits for a loaded production box.

Text
out[5] = 11.0

Two fixes work: declare t inside the loop body, where it is private by construction, or write private(t). Declaring at the point of first use is the cleaner of the two. The loop variable i is the one exception OpenMP privatizes for you, and the loop variable of a nested for inside the parallel loop is also private only when declared in the for statement itself.

lastprivate carries a value out

After a loop, a private variable is gone. lastprivate copies the value from the logically last iteration back into the original.

lastprivate.cc
#include <stdio.h>

int main(void) {
    int last = -1;

    #pragma omp parallel for lastprivate(last)
    for (int i = 0; i < 10; i++) {
        last = i * i;
    }

    printf("last = %d\n", last);
    return 0;
}
Text
last = 81

"Last" means the last in sequential order, iteration 9, not the iteration that happened to finish last in time. The output is therefore deterministic: 9 * 9 = 81. If the variable is assigned only in some iterations, lastprivate can return a value from an iteration that did not assign it, so keep the assignment unconditional.

default(none) as a compiler-enforced checklist

default(none) removes the implicit rules. Every variable that appears in the construct and was declared outside it must now be named in a clause, or the compile fails. This turns the question "did we decide how this variable is shared" into an error message.

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 5.0 

Leave out scale from the clauses and GCC stops:

Text
default-none.c:10:9: error: 'scale' not specified in enclosing 'parallel'

The exact wording and column vary between compiler versions, but the shape is constant: the variable is named and the clause that is missing is the one you were asked to decide. The loop variable i needs no entry, because it is predetermined private. Note the C-specific caveat: const-qualified variables with no mutable members were predetermined shared in OpenMP 3.x and are not in 4.0 and later, so code that lists them in shared on an old compiler and omits them on a new one is the usual source of a build that works on one machine and errors on another. Name them in shared and both compilers accept it.

A rule you can apply without thinking

For each variable used inside the construct, ask these in order.

  1. Is it declared inside the construct? Then it is private already. Move declarations in when you can.

  2. Is it written by more than one iteration at the same place? That is a bug, or a reduction. Use reduction.

  3. Is it an array or structure with each iteration touching its own element? shared.

  4. Is it read only? shared, or firstprivate if it is a small scalar you want copied.

  5. Is it scratch space that each iteration writes before it reads? private.

  6. Is it scratch space that needs the outer value to start? firstprivate.

  7. Is it needed after the loop, from the last iteration? lastprivate.

Then write default(none) so the compiler checks that you answered every question. On a function body of 30 lines this takes a minute, and it removes a whole class of bug before the first run.

What these attributes do not fix

Scoping decides copies, not ordering. Two iterations that both write the same element of a shared array are still a race, and default(none) will not notice. Pointer variables are a special case: private(p) gives each thread its own pointer, but the memory it points to is still shared, so private(buf) where buf is a double * does not give each thread a buffer. Allocate inside the region instead. Finding what the compiler cannot find is a job for a tool, covered in detecting data races with ThreadSanitizer.

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

Also inDebugging
Share

Keep reading

Get new posts by email

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

Unsubscribe in one click. No spam, ever.