In: Computer Science
Can the following code be modified to use a mutex lock rather than a semaphore? Why or why not? (sem_post() is the POSIX form of signal())
sem_t sem;
sem_init(&sem, 0, 1);
sem_wait(&sem);
// critical section
sem_post(&sem);
sem_destroy(&sem);
Critical Section - It is simply defined as an area in the code where shared resources can be accessed. Two or more processes can access the same resource. This creates a problem called the critical section problem when two processes want to access the resource simultaneously. To solve this problem, two mechanisms are used one is a semaphore and the other is a mutex.
Semaphore - A Semaphore is a signaling mechanism that is used in synchronization operations in computer systems, A Semaphore is used to solve critical section problem by using two atomic operations signal and wait.
Mutex - Mutex is a locking mechanism that uses a mutex lock on a resource. The mutex is used to ensure that only one thread is allowed in the critical section and use the resource.
Answer:
The following code cannot be modified to use a mutex lock because the following piece of code uses binary semaphore and a mutex can never act as a semaphore.
Lets break the code to understand better;
sem_t sem; - Here we declare a semaphore where sem_t is the typedef.
sem_init( &sem , 0 , 1 ) - Intialization of the binary semaphore *sem. A binary semaphore only uses 1 and 0 to signal. If 1 then wait operation is implemented and 0 when the signal operation is successful
sem_wait(&sem) - This implements the wait function on the semaphore *sem
critical section - The area of code where shared resources can be accessed.
sem_post(&sem) - This implements the post function on *sem. On success, it return's 0, and on failure, the return value is -1.
sem_destroy(&sem) - Semaphore *sem is destroyed and memoy is deallocated.