skip to content
Ivan's wiki
Site Tools
Search
Tools
Show pagesource
Backlinks
Recent Changes
Media Manager
Sitemap
>
Recent Changes
Media Manager
Sitemap
openmp-atomic
This page is read only. You can view the source, but not change it.
# OpenMP atomic **[Atomic](https://hpc-tutorials.llnl.gov/openmp/atomic_directive/)** in OpenMP protects a single read-modify-write operation like `count++` without taking a full mutex, mapping to a hardware atomic instruction where available (e.g. `lock xadd` on x86) and thus much cheaper than [\`critical\`](/openmp-critical-sections). This fixes the classic race condition where `count++` compiles to three instructions (load, increment, store) and multiple threads executing simultaneously can load the same value, both increment, and both store back, resulting in one increment instead of two. ```c #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.
Page Tools
Show pagesource
Backlinks
Back to top