Push onto a lock-free stack with a compare-and-swap loop
Push onto a lock-free stack with a compare_exchange_weak loop in C++17, where a failed CAS refreshes the node's next pointer for the retry.
A lock-free stack needs only one shared word, the head pointer. To push, you point the new node at the current head and then swing the head to the new node, but only if nobody changed it meanwhile. That is a compare-and-swap in a loop. The neat detail is that compare_exchange_weak writes the current head into its first argument when it fails, so the new node's next is already refreshed for the retry.
#include <atomic>
#include <cstdio>
#include <thread>
struct Node { int value; Node *next; };
std::atomic<Node *> head{nullptr};
void push(int v)
{
Node *n = new Node{v, head.load(std::memory_order_relaxed)};
while (!head.compare_exchange_weak(n->next, n,
std::memory_order_release,
std::memory_order_relaxed))
; // n->next now holds the new head; try again
}
int main()
{
std::thread t[4];
for (int i = 0; i < 4; i++)
t[i] = std::thread([i] { for (int j = 0; j < 1000; j++) push(i * 1000 + j); });
for (auto &x : t) x.join();
int count = 0;
for (Node *p = head.load(); p;) { Node *next = p->next; delete p; p = next; count++; }
std::printf("nodes=%d\n", count);
}nodes=4000Pushing is the easy half. Popping is hard because between reading head->next and swapping the head, another thread can pop and reuse the same node address, so the CAS succeeds on stale data; this is the ABA problem, and it is why a lock-free pop needs tagged indices, hazard pointers or epochs. Build with GCC 13 and -std=c++17 -pthread. See compare_exchange.