Atomic Increment Ordering: relaxed vs. seq_cst
Question 2 / 51 • Correct so far: 0 (0 answered)
Relaxed Increment
static void incrementRelaxed(std::atomic<int>& counter, int n) {
for (int i = 0; i < n; ++i)
counter.fetch_add(1, std::memory_order_relaxed);
}
incrementRelaxed(counter, kIterations); Seqcst Increment
static void incrementSeqCst(std::atomic<int>& counter, int n) {
for (int i = 0; i < n; ++i)
counter.fetch_add(1);
}
incrementSeqCst(counter, kIterations); Shared test data (shared-setup)
constexpr int kIterations = 65536; Which snippet is faster? (Assume x86-64)
Both snippets perform the same on x86. The x86 LOCK prefix required for fetch_add provides acquire-release semantics regardless of the requested memory order; the hardware gives seq_cst for free on this ISA.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Relaxed Increment | 84.6 us | 1.0× |
| Seqcst Increment | 81.5 us | 1.0× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.