Explain Mutex in Detail and its mechanism?

Subject : Microcontroller and Embedded Programming

Topic : Embedded/Real Time Operating System

Difficulty : Medium

1 Answer

MUTEX: Mutex is the short form for mutual exclusion. It is used for resource and task synchronization. It is a special binary semaphore that can be in a locked or unlocked state.

A task acquires or locks a mutex whenever required, uses the resources, and finally unlocks or releases the same. In this case the owner of the semaphore will be a particular task and this task can acquire particular resources for multiple times. Another task will not be able to acquire the resource if it is not the owner of the mutex.

Fig(c) shows the example of mutex. In the above fig the task ’A’ has multiple lock counts and the semaphore once acquired by task ’A’ cannot be acquired by other task.

If the owner acquires or locks the mutex for ‘x’ times then the task has to also release for ‘x’ times. A task that owns the mutex cannot be deleted unless and until it releases all the mutexes.

enter image description here

Mutex can be achieved by following mechanisms:

  1. Disabling the interrupts: In this case when the interrupts are disabled, the tasks that are in waiting state will not be able to reach to the ready to run state. Hence the critical section of the task in running state will be completed and then the interrupts will be enabled. Thus the mutual exclusion will be achieved.

  2. Disabling the scheduler: In this case the scheduler is disabled, so it will not be able to schedule any task to running task. Thus the critical part of the code will be executed with mutual exclusion and then the scheduler will be enabled again. But this can cause major problem if some problem occurs with the task that disables the scheduler. In such cases the scheduler will never be enabled and hence the system may behave abruptly.

  3. Test and set operations: The test and set operations can be implemented by testing a particular global variable to find whether the shared resource is available or not. For example there may be a global variable which will be initially ‘0’ and whenever uses a resource corresponding global variable will be set to ‘1’ by that task. Thus if another task tests for the availability of the resource by checking the global variable, it will get the information that the task is used by some other task and hence is not available. The procedure for accessing the shared resource can be as given below: a. disable the interrupts b. set the global variable corresponding to the resource to be acquired c. use the shared resource d. reset or clear the global variable corresponding to the resource used e. enable the interrupts

The function calls required to work with mutex are:

a. Create a mutex

b. Delete a mutex

c. Acquire a mutex

d. Release a mutex

e. Query a mutex

f. Wait on a mutex

Please log in to add an answer.