Site Tools


atomic-openmp

Table of Contents

Atomic (OpenMP)

count++ compiles to three instructions: load, increment, store. When two threads execute this simultaneously, both can load the same value, both increment it, and both store back — the net result is one increment instead of two. This is the classic read-modify-write race condition.

Atomic in OpenMP protects a single operation like this without taking a full mutex. It maps to a hardware atomic instruction where available (e.g. lock xadd on x86), making it much cheaper than `critical`.

#pragma omp parallel for
for (int i = 0; i < N; i++) {
    #pragma omp atomic
    count += contribution(i);
}

The statement following atomic must be a simple update of the form x op= expr, x++, or x--. For anything more complex, such as updating two variables together or protecting a block of statements, use critical instead. atomic only guarantees atomicity of that one operation; it does not impose a memory ordering barrier on surrounding code unless seq_cst is specified.

atomic-openmp.txt · Last modified: by 127.0.0.1