# `cmpxchg`

[x86-64 Documentation](https://asm-editor.specy.app/documentation/x86.md) › [Instructions](https://asm-editor.specy.app/documentation/x86/instruction.md)

Web page: https://asm-editor.specy.app/documentation/x86/instruction/cmpxchg

**Compare and exchange**

Category: Atomic

Compares the accumulator (al, ax, eax or rax) with the destination; if equal, stores the source there and sets ZF, else clears ZF and loads the destination into the accumulator.

486 and later · accepts the `lock` prefix with a memory operand

[Intel's reference: CMPXCHG](https://intel.github.io/SDM/instruction/CMPXCHG.html)

## Flags

| Flag | Effect |
| --- | --- |
| CF | depends on the result |
| PF | depends on the result |
| AF | depends on the result |
| ZF | depends on the result |
| SF | depends on the result |
| DF | not changed |
| OF | depends on the result |

## Forms

- `cmpxchg r/m, reg` (8, 16, 32, 64)
  - `cmpxchg r/m8, reg8`: Pentium and later
  - `cmpxchg r/m16, reg16`: Pentium and later
  - `cmpxchg r/m32, reg32`: Pentium and later
  - `cmpxchg r/m64, reg64`

## Operands

- `r/m`: A general-purpose register or memory location matching the operation’s size, for example `rax` or `qword [rbp-8]`.
- `reg`: A general-purpose register matching the operation’s size, for example `al`, `ax`, `eax` or `rax`.

## Description

The accumulator is `al`, `ax`, `eax` or `rax`, by operand size. On a match it stores the source register into the destination and sets ZF; otherwise it clears ZF and loads the destination's value into the accumulator. The other arithmetic flags are set as `cmp` would set them for the accumulator and the destination.

The destination can be a register or memory. With a memory destination and a `lock` prefix the whole compare and store is atomic, which is how a value shared between threads is updated safely: load it into `rax`, compute the new value in another register such as `rbx`, then `lock cmpxchg [value], rbx`. ZF set means the store happened. ZF clear means another thread changed the value first, and `rax` now holds its new value, ready for another attempt.

## Example

```x86
global _start

section .text
_start:
        mov rax, 12
        mov rbx, 5
        mov rcx, 3
        mov rsi, 9

        cmpxchg rax, rbx

        mov rax, 60         ; syscall 60: exit
        xor rdi, rdi
        syscall
```
