Atomic 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`. 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.
#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.