ST
StateTrace
Visual Quant & Low-Latency Systems Lab
GitHub
Concepts/Synchronization/Shared Counter

Shared Counter

Trace how different synchronization approaches affect correctness and latency. Step through the same workload three ways and see where shared state goes wrong.

Steps
1/4
Stateshared + per-thread
T1
T1 local
statusidle
shared
shared memoryread
counter0
counter per stepnow = 0
T2
T2 local
statusidle
Per increment52.9nsmedian of 10 reps
Correctness all updates landed4,000,000 / 4,000,000
vs Non-Atomic21× slowersame workload, correct result
Setup4 threadsCPP · 1M iters · Apple M1 Pro
OBSERVED

An atomic counter is initialised to 0.

Atomic
1#include <atomic>
2
3std::atomic<int64_t> counter{0};
4
5void worker() {
6    counter.fetch_add(1, std::memory_order_relaxed);
7}
Historystep 1 / 4
step 1/4
Atomic. 52.94 ns / op. Mutex costs 2.1× more for the same result.