Hard
A CAS retry loop with no backoff under heavy contention
Eight threads all repeatedly increment the same std::atomic<int> via a naive compare_exchange_weak retry loop with no backoff, as shown. Under heavy contention (many more threads than cores, all hammering the same atomic), what actually happens to throughput, and does this count as a correctness bug the way livelock or deadlock does?
main.cpp
std::atomic<int> counter{0};
void bump() {
int old = counter.load(std::memory_order_relaxed);
while (!counter.compare_exchange_weak(
old, old + 1, std::memory_order_relaxed)) {
// retry immediately: no pause, no backoff
}
}
// 8 threads each call bump() in a tight loop, millions of times37 of 51 in Concurrency