Compare-exchange
- C++ course
- Advanced
- Lesson 27/83
- 5 min
Learn atomic compare-and-swap with compare_exchange.
Compare-exchange
compare_exchange_strong is an atomic compare-and-swap (CAS). If the expected value expected equals the atomic value, it sets the atomic to desired and returns true. Otherwise it sets expected to the atomic value and returns false.
The syntax is a.compare_exchange_strong(expected, desired). The operation is indivisible; no other thread can sneak in. CAS is the cornerstone of lock-free data structures (lock-free stack, queue). compare_exchange_weak may spuriously fail; it is used inside loops.
CAS loop
CAS is usually wrapped in a loop. When compare_exchange_strong returns false, expected now holds the current atomic value; the user computes a new desired and tries again. This is the optimistic update pattern.
Example: to increment a lock-free counter write do { expected = a.load(); desired = expected + 1; } while (!a.compare_exchange_strong(expected, desired));. If another thread interfered the loop retries; otherwise it finishes in one step. This is the basis of mutex-free synchronization.
Practice CAS 5 to 10
Create std::atomic<int> a{5};. Declare int expected = 5;. Try the swap with bool ok = a.compare_exchange_strong(expected, 10);. Write std::cout << ok << " " << a.load();.
Starter code
#include <iostream>
#include <atomic>
int main() {
// Create atomic, do CAS, print result
return 0;
}Sample solution
#include <iostream>
#include <atomic>
int main() {
std::atomic<int> a{5};
int expected = 5;
bool ok = a.compare_exchange_strong(expected, 10);
std::cout << ok << " " << a.load();
return 0;
}Expected output
1 10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does compare_exchange_strong return?
bool ok = a.compare_exchange_strong(expected, desired);- The new value
- The old value
- A success bool Correct answer
- The atomic type
Explanation: compare_exchange_strong returns a bool; true means the swap happened.
2 Match each piece to its role
| Term | Meaning |
|---|---|
expected |
Expected value |
desired |
New value |
a.compare_exchange_strong |
The CAS operation |
bool ok = ... |
Result (success) |
3 Complete the compare_exchange line
std::atomic<int> a{5};
int expected = 5;
bool ok = a.____(expected, 10);
std::atomic<int> a{5};
int expected = 5;
bool ok = a.compare_exchange_strong(expected, 10);
Explanation: compare_exchange_strong(expected, 10) performs the swap.