Skip to content

Unit 11 · Data Sharing in a Parallel World

3 h contact · 6 h self study Prerequisites: Units 9 and 10 CLO 4

1. Setting the scene

Scenario: The report that is almost always right

After parallelising the SensorGrid aggregation, the daily totals look correct. But once or twice a week the number of readings is a few thousand too low. Rerunning the job gives the right answer. Nobody can reproduce the error on a laptop.

This is the signature of a data race: a bug that depends on timing.

Guiding questions

  1. Which variables do threads share by default, and which are private?
  2. Why does a race appear only sometimes, and only with many threads?
  3. How do we make a program race free without making it slow?

2. Intended learning outcomes

# Outcome Bloom CLO
ILO 11.1 Define a data race and explain why it causes non deterministic results. UNDERSTAND 4
ILO 11.2 Apply the data sharing clauses private, firstprivate, shared and default. APPLY 4
ILO 11.3 Choose between critical, atomic and reduction to protect shared updates. EVALUATE 4
ILO 11.4 Diagnose races in existing code. ANALYSE 4

3. Imposters in the hello world

Look again at the hello world, written slightly differently:

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

int main(void) {
    int nthreads, tid;                     /* declared OUTSIDE the parallel region */
    #pragma omp parallel
    {
        tid = omp_get_thread_num();
        nthreads = omp_get_num_threads();
        printf("Hello, I'm thread %d of %d.\n", tid, nthreads);
    }
    return 0;
}

Most of the time the output is as expected. But occasionally:

$ OMP_NUM_THREADS=4 ./example
Hello, I'm thread 2 of 4.
Hello, I'm thread 2 of 4.
Hello, I'm thread 2 of 4.
Hello, I'm thread 3 of 4.

Imposters are pretending to be thread 2. What went wrong?

Default rule

All variables declared outside a parallel construct are shared by all threads by default.

There is only one tid. Every thread writes its id into it and then reads it back, and between the write and the read another thread may overwrite it:

sequenceDiagram
    participant T0 as Thread 0
    participant T1 as Thread 1
    participant T2 as Thread 2
    participant V as shared tid
    T0->>V: tid = 0
    T1->>V: tid = 1
    T2->>V: tid = 2
    T0->>V: read tid → 2
    Note over T0: prints "thread 2"
    T1->>V: read tid → 2
    Note over T1: prints "thread 2"
    T2->>V: read tid → 2

4. Data races

Definition

A data race occurs when two or more threads access the same memory location concurrently, and at least one of the accesses is a write.

Why x + 1 twice can give 1

x++ is not one step. It is load, add, store:

sequenceDiagram
    participant A as Thread A
    participant X as x (memory)
    participant B as Thread B
    Note over X: x = 0
    A->>X: load x → 0
    B->>X: load x → 0
    A->>A: 0 + 1 = 1
    B->>B: 0 + 1 = 1
    A->>X: store 1
    B->>X: store 1
    Note over X: x = 1, but 2 was expected

One update is lost. If \(p\) threads each increment a shared counter \(N/p\) times without protection, the final value satisfies

\[ N/p \;\le\; \text{result} \;\le\; N \qquad\text{(in practice: anywhere in between)} \]

Why races are hard to find

Extra care is needed because races are not always easy to spot:

  • with floating point data, a wrong result may look like a numerical side effect;
  • changing the number of threads can make the problem seem to appear or disappear;
  • the outcome may depend on the load on the system;
  • the race may only show up with many threads.

Of the possible interleavings of two threads that each execute \(k\) steps, there are

\[ \binom{2k}{k} \]

orderings; for three steps each that is already 20, and only some of them are wrong. Testing a few runs rarely hits the bad ones.

Rule: only share data that is not modified by other threads, or protect every modification.

5. The fix: declare the variables private

#pragma omp parallel private(nthreads, tid)
{
    tid = omp_get_thread_num();
    nthreads = omp_get_num_threads();
    printf("Hello, I'm thread %d of %d.\n", tid, nthreads);
}

Now every thread has its own tid and nthreads. (Declaring them inside the block, as in Unit 9, has the same effect: variables declared inside a parallel region are private.)

6. Data sharing attributes

flowchart TB
    Q{"Does each thread need<br/>its own copy?"} -->|"no, one copy for all"| SH["shared(list)<br/>default for variables declared outside"]
    Q -->|"yes"| Q2{"Must the copy start with<br/>the value from before the region?"}
    Q2 -->|"no"| PR["private(list)<br/>initial value undefined"]
    Q2 -->|"yes"| FP["firstprivate(list)<br/>initialised with the outside value"]
Clause Each thread has Initial value inside Typical use
private(list) its own copy undefined loop temporaries, thread ids
firstprivate(list) its own copy the value before the region parameters each thread modifies locally
shared(list) one copy for all (the default) the outside value read only input arrays, results written by index
default(shared \| none) changes the default none forces you to declare every variable

Use default(none)

default(none) makes the compiler reject any variable whose sharing you did not state explicitly. It turns silent races into compile errors.

Example

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

int main(void) {
    int a = 10, b = 20, c = 30;
    #pragma omp parallel num_threads(2) default(none) private(a) firstprivate(b) shared(c)
    {
        int tid = omp_get_thread_num();
        a = tid;            /* private: undefined on entry, must be set first */
        b += tid;           /* firstprivate: starts at 20 in every thread     */
        #pragma omp critical
        c += 1;             /* shared: one copy, protected update             */
        printf("thread %d: a=%d b=%d\n", tid, a, b);
    }
    printf("after: a=%d b=%d c=%d\n", a, b, c);
    return 0;
}
thread 0: a=0 b=20
thread 1: a=1 b=21
after: a=10 b=20 c=32

After the region, the original a and b are unchanged (the threads modified their own copies); c was shared, so both increments are visible.

7. Protecting shared updates

When threads must update a shared variable, OpenMP offers three tools:

#pragma omp parallel for
for (int i = 0; i < N; i++) racy++;                 /* data race */

#pragma omp parallel for
for (int i = 0; i < N; i++) {
    #pragma omp atomic
    atomic_count++;                                  /* correct, but contended */
}

#pragma omp parallel for reduction(+:reduced)
for (int i = 0; i < N; i++) reduced++;              /* correct and fast */
racy=500000 atomic=1000000 reduction=1000000        (the racy value changes every run)
Tool Protects Cost Use when
critical any block of code, one thread at a time high: threads queue complex updates (several variables, a list append)
atomic a single memory update (x++, x += v) lower: hardware atomic instruction simple scalar updates
reduction(op:var) partial results combined at the end lowest: no contention in the loop sums, products, min, max
gantt
    title Why critical sections serialise work (4 threads)
    dateFormat X
    axisFormat %s
    section Thread 0
    compute :0, 4
    critical :crit, 4, 5
    section Thread 1
    compute :0, 4
    wait :4, 5
    critical :crit, 5, 6
    section Thread 2
    compute :0, 4
    wait :4, 6
    critical :crit, 6, 7
    section Thread 3
    compute :0, 4
    wait :4, 7
    critical :crit, 7, 8

If a fraction \(c\) of each thread's work sits inside a critical section, that fraction is effectively sequential, and Amdahl's law applies to it:

\[ S(p) \le \frac{1}{c + \dfrac{1 - c}{p}} \]

8. Classwork: find the races

Which lines race? How do you fix them? (25 min)

double sum = 0.0, tmp;
int count[24] = {0};                         /* readings per hour */
#pragma omp parallel for
for (long i = 0; i < n; i++) {
    tmp = pm25[i] * calib;                   /* (1) */
    sum += tmp;                              /* (2) */
    count[hour[i]]++;                        /* (3) */
    out[i] = tmp;                            /* (4) */
}
Solution

(1) tmp is shared: race; make it private(tmp) or declare it inside the loop. (2) sum is shared and written by all: use reduction(+:sum). (3) Different iterations may have the same hour[i]: race; use #pragma omp atomic or an array reduction reduction(+:count[:24]). (4) Each iteration writes a different out[i]: no race. pm25, calib, hour are only read: safe to share.

9. Check your understanding

What is the initial value of a private variable inside the region?

Undefined. Use firstprivate if the value from before the region is needed.

Is a loop that only reads a shared array and writes out[i] racy?

No. Concurrent reads are safe, and each iteration writes a distinct element.

Why is reduction usually faster than atomic for a sum?

Each thread accumulates into a private copy without synchronisation; the copies are combined once at the end instead of synchronising on every iteration.

10. Key takeaways

  • Variables declared outside a parallel region are shared by default.
  • A data race: concurrent access to one location, at least one write. It causes lost updates and non deterministic results.
  • Make per thread data private (or declare it inside the region); use firstprivate to keep the initial value.
  • Protect shared updates with critical, atomic or, best, reduction.
  • Use default(none) to force explicit decisions.

Every portfolio OpenMP program must use default(none) and must be run with a thread sanitizer (gcc -fopenmp -fsanitize=thread) or equivalent; report what it found.

Further reading

  • O. Louant, OpenMP training, CISM/CÉCI.
  • H. Boehm (2011), How to miscompile programs with "benign" data races, HotPar.