0Pricing
C++ Academy · Lesson

Compare-and-Swap CAS Patterns

Implement lock-free updates with compare_exchange_weak and strong.

Compare-and-Swap CAS Patterns is a free C++ Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The CAS Primitive

Compare-and-swap atomically reads, compares, and conditionally writes. The foundation of most lock-free algorithms.

C++ Compare Exchange

Two variants in std::atomic:

  • compare_exchange_strong(expected, desired) — succeeds when current equals expected
  • compare_exchange_weak(expected, desired) — may fail spuriously

Anatomy of a CAS Loop

The classic CAS loop: read, compute, attempt to write. Retry if another thread won the race.

std::atomic<int> a{0};

int old = a.load();
int next;
do {
    next = compute_new(old);
} while (!a.compare_exchange_weak(old, next));

CAS for Atomic Update

Use CAS when the new value depends on the old. Plain store would lose updates from concurrent threads.

// Atomic max
int current = a.load();
while (newval > current && !a.compare_exchange_weak(current, newval));

Lock-Free Stack: Push

A simple lock-free stack push uses CAS to install a new node at the head.

struct Node { int value; Node* next; };
std::atomic<Node*> head{nullptr};

void push(int v) {
    Node* n = new Node{v, nullptr};
    n->next = head.load();
    while (!head.compare_exchange_weak(n->next, n));
}

Spurious Failure

compare_exchange_weak may fail even when values match — on platforms like ARM where the underlying instruction is allowed to fail. Use it inside loops; use strong when retrying is expensive.

Update Pattern: Reset

To reset a value to a known state only if it has not changed.

int expected = 42;
if (a.compare_exchange_strong(expected, 0)) {
    // a was 42 and is now 0
}

Building Block: Atomic Counter

For a plain counter, fetch_add is simpler and faster than a CAS loop.

Building Block: Atomic Flag

For a simple boolean flag, std::atomic_flag is lighter than std::atomic<bool> and supports test_and_set.

Reasoning About Concurrency

Lock-free code is famously hard to reason about. Use rigorous testing (TSan, fuzzing), formal models when available, and prefer existing battle-tested implementations.

When to Choose CAS

Use CAS when:

  • Multiple threads update the same value frequently
  • Mutexes show contention as a bottleneck
  • The critical section is very short and simple

When Not to Use CAS

Avoid CAS when:

  • The update needs more than a couple of operations
  • Correctness is more important than throughput
  • The team lacks expertise in lock-free programming

Quick Check

Why do we typically use compare_exchange_weak inside a loop?

Recap

Compare-and-swap atomically updates a value only if it equals an expected value. CAS loops handle concurrent updates without locks. Use compare_exchange_weak inside loops, strong for one-shot attempts.

Frequently asked questions

Is the “Compare-and-Swap CAS Patterns” lesson free?

Yes — the full text of “Compare-and-Swap CAS Patterns” is free to read here on the web, and the C++ Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C++ Academy course, upgrade to CoddyKit PRO.

What will I learn in “Compare-and-Swap CAS Patterns”?

Implement lock-free updates with compare_exchange_weak and strong. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C++ Academy?

No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Compare-and-Swap CAS Patterns” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C++ Academy lesson?

Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. std::atomic and Memory Orders
  2. Compare-and-Swap CAS Patterns
  3. Lock-Free Queue Implementation
  4. Hazard Pointers and the ABA Problem
← Back to C++ Academy