Hard
Choosing between the weak and strong CAS
push() below uses compare_exchange_weak inside a while loop to publish a new head node onto a lock-free stack. Why is compare_exchange_weak preferred here over compare_exchange_strong, and what would go wrong if the exact same call were instead used once, outside any loop, inside a plain if?
stack.cpp
#include <atomic>
struct Node { int value; Node* next; };
std::atomic<Node*> head{nullptr};
void push(Node* n) {
n->next = head.load(std::memory_order_relaxed);
while (!head.compare_exchange_weak(
n->next, n,
std::memory_order_release,
std::memory_order_relaxed)) {
// on failure, n->next has been updated to the current head; retry
}
}70 of 117 in C++