Backend & systems·Concurrency and coordination
you update the value only if it still equals what you last read, and loop round to try again if somebody beat you to it.
Compare-and-swap
Also calledCAS, atomic compare and set
An atomic primitive that sets a value only if it currently matches an expected one. It is the basis of lock-free algorithms and of optimistic concurrency at every layer, from CPU instructions to conditional writes in a key-value store. Under high contention the retry loop can waste more CPU than a lock would have cost.