How to use mutex lock to make data-structure thread safe?

26 Aug, 2020


This tutorial needs basic understanding of C programming and mutex lock concept as prerequisites.

This is just a basic introduction - making highly efficient thread safe data-structure requires its own book.
making things thread safe is very important in system level stuff.
Let's take an example obviously it would be code =)
#include <stdio.h> #define SIZE 10 int stack[SIZE]; int top;
void push(int x) {     stack[top++] = x; } int pop() {     return stack[--top]; } int main(void) { }

in this above code stack is not thread safe. beacuse if somehow two threads call push() and pop() function at
the same time then the data or the stack can be incosistent.
For example, if two threads call pop() at the same time then both threads may read same value beacuse of the
same value of top (pointer(index) which pointing to top of the stack )

To make things thread safe, firstly we have to identify the critical section or critical section code/instructions.