Thread-Safe Counter: Two Synchronization Approaches
Question 24 / 51 • Correct so far: 0 (0 answered)
Mutex Counter
void increment() {
std::lock_guard<std::mutex> lock(g_mutex);
++g_counter;
}
increment(); Atomic Counter
void increment() {
g_counter.fetch_add(1, std::memory_order_relaxed);
}
increment(); Shared test data (shared-setup)
// (no shared data; each variant owns its counter) Which snippet is faster?
Snippet B is faster. Atomic increment uses a single hardware operation, while a contended mutex adds lock/unlock and scheduling overhead. For a simple shared counter, that extra coordination makes the mutex path slower.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Atomic Counter | 7.26 ns | 3.8× |
| Mutex Counter | 27.2 ns | 1.0× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.