Skip to content
EntityQ128562· pop 12· linked from 51 articles

compare-and-swap

Sign in to save

Also known as CAS

In computer science, compare-and-swap (CAS) is an atomic instruction used in multithreading to achieve synchronization. It compares the contents of a memory location with a given (the previous) value and, only if they are the same, modifies the contents of that memory location to a new given value. This is done as a single atomic operation. The atomicity guarantees that the new value is calculated based on up-to-date information; if the value had been updated by another thread in the meantime, the write would fail. The result of the operation must indicate whether it performed the substitution

~13 min read

Encyclopedic overview

10 sections
Contents
  • Overview
  • Example application: atomic adder
  • ABA problem
  • Costs and benefits
  • Implementations
  • Implementation in C
  • Extensions
  • See also
  • References
  • External links

In computer science, compare-and-swap (CAS) is an atomic instruction used in multithreading to achieve synchronization. It compares the contents of a memory location with a given (the previous) value and, only if they are the same, modifies the contents of that memory location to a new given value. This is done as a single atomic operation. The atomicity guarantees that the new value is calculated based on up-to-date information; if the value had been updated by another thread in the meantime, the write would fail. The result of the operation must indicate whether it performed the substitution; this can be done either with a simple boolean response (this variant is often called compare-and-set), or by returning the value read from the memory location (not the value written to it), thus "swapping" the read and written values.

==Overview== A compare-and-swap operation is an atomic version of the following pseudocode, where denotes access through a pointer:

Excerpted from Wikipedia’s “compare-and-swap” article, available under the CC BY-SA 4.0 licence.