Skip to content

CAS Lock

  • Lock Free
  • CAS = Compare And Swap

Pseudo Code

Since CAS operation need to be atomic, we need hardware support.

cpp
bool CAS(int* p, int oldValue, int newValue) {
    if (*p != oldValue) {
        // someone modified after getting value
        return false;
    }
    // ok no one modified after getting value, go!
    *p = newValue;
    return true;
}

Use Case

Swap new value, fail then retry.

cpp
int oldValue, newValue;
do {
    oldValue = p;
    // something not atomic
    newValue = NEW_VALUE;
} while(!CAS(&p, oldValue, newValue)); // Fail? Retry!

CAS in STL

Atomically compares with expected. If those are equal, replaces with desired. Otherwise, loads the actual value into expected.

bool std::atomic<T>::compare_exchange_weak(T& expected, T desired, ...)
bool std::atomic<T>::compare_exchange_strong(T& expected, T desired, ...)

Changelog

Just observe 👀