Course contentsShow
← C
Lesson 1145 of 1,21915. Systems ProgrammingFree lesson

Compare and swap (CAS) basics

Compare and swap (CAS) basics

What you'll learn: How to update a shared variable safely without using a heavy-weight mutex lock.

The problem with "Read-Modify-Write"

In systems programming, a simple line like counter++; is dangerous. Under the hood, the CPU must read the value, add one, and write it back. If two threads do this at the exact same time, they might both read "5," both calculate "6," and both write "6" back. One increment is lost.

Usually, we use a Mutex (a lock) to stop this. But locks are heavy; they tell the operating system to put threads to sleep, which is slow. Compare and Swap (CAS) is a "lock-free" alternative built directly into the CPU hardware.

How CAS works

Think of CAS as a "smart update" that asks a question before it commits. Instead of just saying "set this to 10," the CPU says: "I think the current value is 5. If it is still 5, change it to 10. If it changed to something else while I wasn't looking, do nothing and tell me I failed."

This is an atomic operation. The CPU guarantees that the "check" and the "set" happen in one single, uninterrupted heartbeat.

CAS in Action

In C11, we use atomic_compare_exchange_strong. It takes three things: the memory address, the value we expect to find, and the new value we want to set.

#include <stdatomic.h>
#include <stdbool.h>

void safe_increment(_Atomic int *obj) {
    int expected = atomic_load(obj);
    int desired;

    do {
        desired = expected + 1;
        // If *obj == expected, set *obj = desired and return true.
        // If *obj != expected, load the *actual* current value into 'expected' and return false.
    } while (!atomic_compare_exchange_strong(obj, &expected, desired));
}

The "Retry" Loop

Notice the do-while loop. This is the classic "CAS loop." If another thread sneaks in and changes the value between our read and our write, our CAS fails. Instead of giving up or locking, we simply grab the new expected value and try the calculation again. Because this happens in nanoseconds at the CPU level, it is often much faster than waiting for a Mutex.

Key takeaway

CAS allows for thread-safe updates by only changing a value if it matches what you expected, preventing accidental overwrites in a lock-free way.