Product metrics were undercounting, and marketing happily reported '40% growth' right after the bug was fixed... sorry, 'right after a successful ad campaign'. The cause was simple: ten threads incrementing a bare long. Make the counter honest — std::atomic, no locks.
Implement a Counter that can be incremented from many threads at once and always reports the exact total. Do it without a mutex — use std::atomic. A plain long here loses updates to data races.
std::atomic (no std::mutex / lock)increment() is safe to call concurrently from any number of threadsget() returns the exact number of increments performedlong increment is UB under concurrency)++x on a plain long a data race when threads share it?std::atomic<long>::fetch_add guarantee that ++ on a long does not?A single std::atomic<long> member is enough: increment() does ++value_ (atomic), get() returns value_.load().
Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.