MUTEXes — What are they and where are they used???
A mutex or Mutually Exclusive Semaphore to give it it’s full name is a software construct commonly found within a multi-tasking operating system, especially an RTOS.
The mutex, as with all semaphores, is a means of signalling between threads and works in exactly the same way tokens are used on the railway network to prevent two trains being on the same piece of track at the same time.
The rule on the railway was you cannot proceed along the track unless you have the token. If you don’t have the token you have to wait until the train that has it relinquishes it. Only when you’re in possession of the token can you proceed.
The mutex semaphore works in exactly the same way.
As the thread runs it gets to a point in the application where it needs to access a protected resource (e.g. our railway line). The resource is protected also known as guarded by a mutex and in order to continue execution, the thread needs to take the mutex.
If it successfully takes the mutex, the thread continues to run and gives it back once it’s finished with the resource.
If it fails to take the mutex, execution of the thread is halted by the scheduler and the thread waits or pends until the mutex becomes available.
Using this strategy, resources such as a shared block of memory or a hardware resource are protected from being accessed by two threads at the same time.
Pitfalls with MUTEXes…
Whilst the mutex is a very useful and powerful way or protecting shared resources and synchronising threads, they can introduce other, emergent problems into the system. Once of the most common being Priority Inversion where a high priority task becomes blocked by a lower priority task as it cannot take the semaphore. This article about Priority Inversion provides a lot more detail.