Most strategies have one big picture. They use the compare and replace operation (CAS) in a loop until it succeeds.
For example, consider a stack implemented with a linked list. I chose the implementation of a linked list because it is easy to do at the same time as CAS, but there are other ways to do this. I will use a C-like pseudocode.
Push(T item) { Node node = new Node(); // allocate node memory Node initial; do { initial = head; node.Value = item; node.Next = initial; } while (CompareAndSwap(head, node, initial) != initial); } Pop() { Node node; Node initial; do { initial = head; node = initial.Next; } while (CompareAndSwap(head, node, initial) != initial); T value = initial.Value; delete initial; // deallocate node memory return value; }
In the above code, CompareAndSwap
is a non-blocking atomic operation that replaces a value in a memory address with a new value and returns the old value. If the old value does not match the expected value, you scroll through the loop and try it again.
source share