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/7
Stateshared + per-thread
T1line 7
T1 locallock
statusin CS
shared
shared memory
counter0
mutex.holderT1
counter per stepnow = 0
T2
T2 local
statusrunning
Per increment112nsmedian of 10 reps
Correctness all updates landed4,000,000 / 4,000,000
vs Non-Atomic45× slowersame workload, correct result
Setup4 threadsCPP · 1M iters · Apple M1 Pro
OBSERVED

T1 holds the mutex. The critical section is protected.

Mutex
T1
1#include <mutex>
2
3int64_t counter = 0;
4std::mutex m;
5
6void worker() {
7    std::lock_guard<std::mutex> lock(m);
8    counter = counter + 1;
9}
Historystep 1 / 7
step 1/7
Mutex. 112.36 ns / op. Atomic does the same job at 52.94 ns.