Atomics
Atomic Variable Declaration
Declare a variable with atomic semantics:
atomic int counter = 0; // sequential consistency (default)atomic(relaxed) int flag = 0; // explicit orderingAtomic Expression
A single statement executed atomically:
atomic counter = counter + 1; // atomic load + storeatomic(release) ready = 1; // release storeAtomic Block
All loads and stores inside the block are atomic:
atomic{ counter = counter + 1; total = total + value;}
atomic(acquire){ int val = sharedData; // acquire load}Memory Ordering
| Mode | Keyword | Description |
|---|---|---|
| Sequentially Consistent | seqcst (default) | Full ordering, strongest guarantee |
| Acquire | acquire | Reads cannot be reordered before this load |
| Release | release | Writes cannot be reordered after this store |
| Acquire-Release | acqrel | Combined acquire + release |
| Relaxed | relaxed | Only atomicity, no ordering guarantee |
Compound Assignment
Compound operators emit single locked instructions (no separate load-op-store):
atomic counter += 1; // LOCK ADDatomic flags &= mask; // LOCK ANDatomic bits |= flag; // LOCK ORatomic value ^= toggle; // LOCK XORatomic count -= 1; // LOCK SUBQualifier Chaining
atomic combines with other qualifiers in any order:
atomic unsafe { ... } // atomic + unsafelock(m) atomic { ... } // lock + atomic (skips try/catch)unsafe atomic { ... } // order doesn't matterWhen lock wraps an atomic block, the try/catch wrapper is skipped for performance since atomic blocks cannot throw.