Lock-free Stack
Stack is a last-in-first-out (LIFO) data structure. We will implement a linked list lock-free stack using the C11 features we learned by far.
Let's see the procedure of pushing a node into a stack.

This works well in a single-thread context, but if other threads are also modifying the stack, it’s not enough. Let's see what would happen if two threads push a node into the stack concurrently.

What can you do about this nasty race condition in a lock-free data-structure? The answer is to use an atomic compare-and-swap (CAS) operation to set the head node to point to your new node. The success of CAS operation ensures that the head hasn’t been modified since you last read it; otherwise, you should retry.
The procedure of pop function can be similarly analyzed. Here is the push and pop function in my_stack.c:
Next, we put the lock-free stack in a multi-threading environment to be accessed as a shared data-structure.
Actually, the print statement is not run together after they push/pop a node, so you may not see the print results in a LIFO order. We should compile the program by using the command:
The program seems perfect, but the program may still abort occasionally when you run it. There is an underlying problem that you may not have noticed. It is called ABA problem to be introduced next.
Last updated
Was this helpful?