3,587 views
struct Semaphore
{
enum value(0,1);
Queue type L;
}

Down (Semaphore S)
{
if(S.value==1)
{
S.value=0;
}
else
{
put process(PCB) in S.L;
sleep();
}
}

Up(Semaphore S)
{
if(S.L is empty)
{
S.value=1;
}
else
{
select a process from S.L;
wakeup();
}
}

I saw this implementation of Binary Semaphore. Is this right?

Consider two processes P0, P1.

P0 performs down first and enters CS. S.value = 0 now.

P1 tries to perform down now and goes to sleep.

P0 comes out and exeutes the else part of Up and wakes P1 up. Now how will Penter the CS, since S.value is still 0?

i think

 S.value=1; this must be there in else part also, i think u missed it

I too think so. I came across this video https://www.youtube.com/watch?v=7kYMPJI7Euo&t=223s and got confused. You are sure this is wrong, right?

Thanks man!! I got worried!!

you can modify the up module as

Up( semaphore s)

{ s=s+1;

if(s<=0)

{

//select a process from from L

wake up ();

}

}
Kindly note that in Binary Semaphore implementation, until block queue of a particular binary semaphore becomes empty, S can't be set to 1.
When there are many processes blocked in the queue of a semaphore (each semaphore variable has its own block queue), process wake up means its PCB has been placed in ready queue, whether it will be executed immediately or later it depends on the CPU scheduling.