Shard a hot counter across threads to cut contention
Split one hot atomic counter into cache-line-padded shards so C++20 threads stop fighting over a single line, then sum the shards when you read.
A single std::atomic<long> that every thread increments is correct and slow: each fetch_add pulls the cache line away from the previous writer. The fix is to give each thread its own slot and add the slots up only when someone asks for the total. This is the same idea as the kernel's per-CPU counters, written with standard C++20 on GCC 14.
#include <atomic>
#include <cstdio>
#include <thread>
#include <vector>
struct alignas(64) Shard { std::atomic<long> n{0}; };
constexpr int kShards = 8;
Shard shards[kShards];
void add(int id) { shards[id % kShards].n.fetch_add(1, std::memory_order_relaxed); }
long total() {
long sum = 0;
for (auto& s : shards) sum += s.n.load(std::memory_order_relaxed);
return sum;
}
int main() {
std::vector<std::thread> ts;
for (int t = 0; t < 4; ++t)
ts.emplace_back([t] { for (int i = 0; i < 1000000; ++i) add(t); });
for (auto& t : ts) t.join();
std::printf("%ld\n", total());
}4000000alignas(64) is what makes this work. Without it, eight adjacent atomic<long> values share one or two cache lines and you have rebuilt the contention you removed, which is false sharing. Relaxed ordering is enough because the counter publishes nothing else, and the join calls give the final read a happens-before edge. A read of total() while writers run is only approximate. Use it for statistics, not for a limit check that must be exact. 64 is the common x86-64 line size; std::hardware_destructive_interference_size names it where your library defines it.