Search code examples
operating-systemsynchronizationsemaphorebinary-semaphore

How does binary semaphore guarantee mutual exclusion?


I just read that binary semaphores guarantee mutual exclusion and that the semaphores can be preempted.

Code for wait/down for binary semaphore(taken from https://www.javatpoint.com/os-binary-semaphore-or-mutex)

Down (semaphore S)   
{  
    if (s.value == 1) // if a slot is available in the   
    //critical section then let the process enter in the queue.   
    {  
        S.value = 0; // initialize the value to 0 so that no other process can read it as 1.   
    }  
    else  
    {  
        put the process (PCB) in S.L; //if no slot is available   
        //then let the process wait in the blocked queue.   
        sleep();   
    }  
}  

so what if a process P1 is running and it checks the condition in the down function and about to change value of s.value to 0,but before it does it is preempted and its PCB is saved and a new process P2 starts running it checks the condition and changes s.value to 0 and its critical section starts.on the other hand P1 may start executing if P2 goes into wait state for I/O and so both may enter their critical sections.So how is mutual exclusion preserved??


Solution

  • Binary semaphores provide mutual exclusion by making sure that the process which changed the value of semaphore to 0 (to show that it is in critical section) is the only process that can change the value of semaphore again (to 1).And so in my question even if P1 starts executing ,then it won't be preempteed. and so it makes sure that P1 will complete before starting P2 if they use a shared resource.. Only counting semaphores can be preempted and they don't guarantee mutual exclusion.