Why use Mutexes?
Mutexes are a technique for concurrency management. They are called Mutex because of their MUTual EXclusion property (Only one thread can be doing work at a given time).
Mutexes are used to prevent race conditions on shared data between threads. Lets look at a stack backed by an array. At some point it could look like this:
If we want to insert a value on this stack we need to follow these steps:
1 – Get the index of the head
2 – Increment the index of the head by one
3 – Save a value in the head
If two threads need to insert a value into this stack at the same time, one of the inserted values could get lost: