CompareExchange
CompareExchange, commonly known as compare-and-swap (CAS), is an atomic operation used in concurrent programming. It compares the value stored at a memory location with an expected value and, if they are equal, replaces the stored value with a new one. The operation is indivisible: it either succeeds and updates the value, or fails and leaves the memory unchanged. Depending on the language or API, the function may report success as a boolean, or return the observed value prior to the attempt.
CAS is a cornerstone of lock-free synchronization. It enables threads to coordinate updates to shared state
Memory ordering is an important aspect of CompareExchange. Many platforms distinguish between strong and weak variants
A common challenge is the ABA problem: the value at the location may change from A to
Common implementations include C11 atomic_compare_exchange and related functions, C++ std::atomic<T>::compare_exchange_weak/strong, Java AtomicReference.compareAndSet, and .NET Interlocked.CompareExchange. Across