Compare-and-Swap

Noun · Development

Definitions

  1. An atomic CPU instruction that compares a memory location to an expected value and, only if they match, replaces it with a new value -- all in one uninterruptible step. The foundation of lock-free algorithms, optimistic locking, and concurrent data structures. If the comparison fails (another thread changed it), the operation retries.

    In plain English: A CPU instruction that says 'change this value, but only if nobody else changed it since I last looked' -- the building block of lock-free code.

    Example: "The atomic counter uses CAS in a loop: read the current value, compute value+1, CAS to set it -- if another thread incremented first, retry."

Related Terms