Hard
Treiber stack pop with a reused node address
Thread 1 begins pop(): it reads head == A and computes newHead = A->next == B, then is preempted right before the compare_exchange_weak call. While preempted, Thread 2 pops A (head becomes B), pops B (head becomes C), then pushes a freshly allocated node that happens to reuse A's old memory address as the new head (head becomes A again, but now A->next == C, not B). Thread 1 resumes and executes compare_exchange_weak(oldHead=A, newHead=B). What happens?
main.cpp
std::atomic<Node*> head;
Node* pop() {
Node* oldHead = head.load();
Node* newHead;
do {
if (!oldHead) return nullptr;
newHead = oldHead->next;
} while (!head.compare_exchange_weak(oldHead, newHead));
return oldHead;
}9 of 51 in Concurrency