Give the correctness argument for a compare and swap loop that atomically raises a running maximum. State which memory orders the success and failure paths need, why the weak form of compare_exchange is used inside a loop, and what progress guarantee the loop actually has.

Give the correctness argument for a compare and swap loop that atomically raises a running maximum. State which memory orders the success and failure paths need, why the weak form of compare_exchange is used inside a loop, and what progress guarantee the loop actually has.

Approach: State the loop invariant on the value written back after a failed exchange, then separate the ordering the update itself needs from the ordering the surrounding data needs.

The loop loads the current value, computes the candidate, and compare exchanges, and on failure the exchange writes the observed value into the local copy so the next iteration recomputes against fresh data, which makes the update atomic under any interleaving; for memory order, success needs release when other writes must be published with it and acquire when later reads depend on it, failure needs at most the acquire part and never release, and the loop is lock free rather than wait free. The weak form may fail spuriously on load-linked store-conditional machines and is cheaper there, and a spurious failure is harmless inside a retry loop. For a running maximum you can skip the exchange whenever the candidate fails to beat the current value, which turns most calls into one relaxed load. Lock free progress means some thread advances, so one thread can be starved indefinitely by others succeeding, which is why this shape degrades sharply above a few writers.

Follow-up: How would you restructure the same update so that 16 writer threads scale, and what accuracy or freshness do you give up?

Key concepts: compare and swap loop, compare_exchange_weak, memory order, lock free progress.