One atomic increment is correct and does not scale, because every thread fights for the same cache line. The ordering that is sufficient and why the default is stronger than needed, the padding that removes contention entirely, and the arithmetic showing when sharding is worth it.
Write a thread-safe counter in C++ that many threads increment. What are the memory-ordering and layout choices?
One atomic increment is correct and does not scale, because every thread fights for the same cache line. The ordering that is sufficient and why the default is stronger than needed, the padding that removes contention entirely, and the arithmetic showing when sharding is worth it.
Updated Sep 2026 · Grounded in real AI infrastructure interview loops and written to a senior-engineer editorial bar, with every number worked and every diagram hand-built.
The concepts behind this question
Ranked by how closely each one overlaps this question's topic, so the first card is the thing to read if the answer above moved too fast.
Scored on relaxed ordering being sufficient for a counter, on false sharing and cache-line padding, and on the sharded design with the read cost that it trades for.
No comments yet — be the first to share your approach.
