Mutex is a variable which is used for handling mutual exclusion in multiple processes which share the same resource. It is a simple form of a semaphore. If TSL or XCHG instruction is present, then mutex can be implemented in user space. A state of a mutex can be locked or unlocked. Value zero represents that the mutex is unlocked and other values represents that the mutex is locked.
Here are the two procedures used with mutex: mutex_lock procedure is called if a process has to enter critical region. mutex_unlock procedure is used if a process has to exit critical region:
Mutex in Pthreads package: If a thread has to enter critical region then it has to lock a mutex. When mutex is unlocked, thread can go ahead and lock it. Now, other threads cannot access this lock. However, if mutex is locked, thread is blocked until the mutext is unlocked.
Here are the calls in Pthreads package for mutex:
- Pthread_mutex_init: It is used for creating a mutex.
- Pthread_mutex_destroy: It is used for destroying an existing mutex.
- Pthread_mutex_lock: It is used for acquiring a lock or block if it is already locked.
- Pthread_mutex_unlock: This call is used for releasing a lock.
- Pthread_mutex_ trylock: This call is used for acquiring a lock or fail with an error code.