Struct Semaphore
{ int value;
Queue type L;
}
Down (Semaphore S)
{
S.value = S.value -1;
if(S.value<0)
{ put process in L;
sleep();
}
else return;
}
Up(Semaphore S)
{ S.value = S.value +1; // line1
if(S.value<=0) //line 2
{ Select a process from L; //line 3
wakeup(); // line 4
}
}
When we are Executing 'Up',
say S.value = -3
now after line 1 S.value is -2
Now it will enter the if-block
and select a process from L (which has 2 processes in it as S.value is -2) and wake up a process
Why does it wake up a process from a sleep when the S.value is still less than 0?
The process which is woken up will try to Execute 'Down' and fail and eventually go back to sleep. Then why was it woken up in the first place? Shouldn't we execute the if block as :
if(S.value>=0)
{select a process from L, wakeup();
}
(I know I'm wrong somewhere, please correct me. I referred Tanenbaum and Galvin but didn't find any such explanation for Counting Semaphores)