Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Compare-and-swap (CAS) is an atomic conditional update: it changes a shared value only if that value still matches what a thread expects. If another thread has changed the value first, the stale update is rejected instead of silently overwriting the newer one. That protects one atomic location—not every part of a concurrent algorithm.

What is compare-and-swap?

A compare-and-swap operation takes an atomic location, an expected old value, and a desired new value. It compares the location with the expected value as one indivisible operation. If they match, it stores the desired value and reports success. If they do not match, it leaves the location unchanged and reports failure. Microsoft documents this conditional-write behavior in its C++ atomic API reference.

In C++, the corresponding API is usually called compare-and-exchange. Its compare-exchange functions take the expected value by reference: when an attempt fails because the actual value differs, the function updates that expected argument with the value it observed. The caller can then use the newly observed value when deciding whether and how to try again.

How does compare-and-swap prevent lost updates?

Imagine a shared counter that starts at 10. Two threads read 10. One plans to add 1, while the other plans to add 2. If both calculate from their separate reads and write unconditionally, one can store 11 and the other can later store 12. The final value is 12, and the first thread’s increment has been lost.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

With CAS, the first thread can conditionally change 10 to 11. The second thread then tries to change 10 to 12, but the current value is 11, so its comparison fails and it does not overwrite 11. If the second increment is still required, that thread must use the current value, calculate again, and retry—changing 11 to 13 in this example. The update is accepted only when the value it was based on is still current.

What happens when compare-and-swap fails?

A failed attempt does not store the desired value. It signals that the caller’s expected state was not current when the atomic operation ran. In C++ compare-exchange, the expected argument is replaced with the value actually observed on a mismatch. Code commonly retries when its operation remains necessary, recalculating from that newer state rather than blindly repeating a stale result.

Rank #2
Theory and Practice of Concurrency
  • Used Book in Good Condition

Failure is a normal outcome when multiple threads compete; it is not necessarily an error. In C++, compare_exchange_strong does not fail spuriously, while compare_exchange_weak may fail even if the expected and actual values compare equal. Weak compare-exchange is therefore commonly used in a retry loop that can tolerate another attempt.

Is compare-and-swap the same as compare-and-exchange?

They refer to the same general conditional-update pattern: compare the current value with an expected value, and replace it only on a match. C++ names its operations compare-exchange, including compare_exchange_strong and compare_exchange_weak. APIs differ in their exact signatures and details, so the C++ behavior should not be assumed for every language or platform.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Does compare-and-swap make code thread-safe?

Not by itself. CAS makes the conditional update to its atomic location indivisible. It does not automatically protect other variables, make a multi-step algorithm atomic, or establish every synchronization relationship the program may need. The algorithm still has to handle retries correctly and coordinate access to any related state.

Atomicity is not the same as memory ordering

Atomicity answers whether another thread can interleave a competing update inside the compare-and-update operation. Memory ordering determines how that operation relates to other memory accesses. The required ordering depends on the API and the relationship the code needs to establish.

For Microsoft’s C++ atomic APIs, ordinary compare-exchange overloads use sequentially consistent ordering; overloads with explicit ordering parameters let the caller select ordering. The failure order cannot be release or acquire-release, and cannot be stronger than the success order. Linux kernel documentation likewise distinguishes unordered atomic operations—which provide atomicity and same-CPU program order—from acquire, release, and stronger ordering guarantees. Neither description means CAS automatically acts as a global barrier for all related data.

CAS loops and locks solve different problems

A CAS loop lets a thread repeatedly attempt an update until it succeeds or its work is no longer needed. Under contention, attempts may fail and require recalculation. A lock instead coordinates access through a separate synchronization mechanism. Which approach is suitable depends on the algorithm and workload; the available API and kernel documentation do not establish that CAS is universally faster than a lock.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Quick Recap

Bestseller No. 2
Theory and Practice of Concurrency
Theory and Practice of Concurrency
Used Book in Good Condition
$74.70
Bestseller No. 3
SaleBestseller No. 5
Straight Outta Comp Sci Parody Computer Science Gift T-Shirt
Straight Outta Comp Sci Parody Computer Science Gift T-Shirt
Lightweight, Classic fit, Double-needle sleeve and bottom hem
$14.44
Best Value
Sale
Straight Outta Comp Sci Parody Computer Science Gift T-Shirt
  • Computer Science Parody design. This Computer Science, Straight Outta Comp Sci Parody apparel is for someone love about the computer, system, software, application, network, and database. Sure they will love this apparel . An awesome gift for everyone.
  • This apparel is the best gift for software application developers, computer systems analysts, computer systems engineers, network systems administrators, database administrators, web developers, programmers, comp sci teachers, and professors.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.