You are currently not logged in and your progress will not be saved. Register or Log in

Mutexes

As opposed to semaphores, mutexes can only take two values, commonly referred to as locked or unlocked. Additionally, mutexes have ownership properties in the sense that only the thread that locks the mutex can unlock it. Think of it as a locking/unlocking mechanism with a single key, where a thread wishing to gain access to a single object. For instance, a code section or a resource needs to first gain access to an unlocked mutex, lock it and then access the object. If the thread trying to gain access to the mutex sees that the mutex is already locked, then the thread gets blocked and will wait until the mutex is unlocked by the thread that locked it.

A typical use of a mutex is to protect a critical section of the code that can be accessed from multiple threads. The critical section is a piece of code that needs to be completed without interruptions from other threads, or else the global/static data within that critical section could be misrepresented or get corrupted.

Mutexes have the following properties:

  • Locking a mutex will increment the lock count. Recursive locking (reentrant locking) will not make the locking thread block since it already owns the mutex. The thread should make sure that it unlocks the mutex the same number of times that it locked it to release the mutex so that other threads can attempt to own it.
  • Unlocking a mutex will decrement the lock count. When the lock count is zero, that means that the mutex is in an unlocked state. Threads can attempt to own the mutex only when the mutex is in an unlocked state.
  • Only the thread that locked the mutex can unlock it.
  • Mutexes locking and unlocking can only be done in threads and not in ISRs. This is because ISRs cannot participate in the ownership and priority inheritance mechanism of the scheduler.
  • The thread locking the mutex is eligible for priority inheritance since only that thread can unlock the mutex.

The figure below shows the mutex properties

Mutex