674 views
0 votes
0 votes
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)

1 Answer

0 votes
0 votes

The negative value in semaphore indicates that no of process tries to enter the cs after cs is occupied.As it is a queue the process stores in FIFO order,when a process exit from cs it perform a wakeup on a process from queue and it enters the cs.
NOTE:In counting semaphores more than one process can  access the shared resource.
if s.value is non negative then process directly enters CS without being block
see for reference https://stackoverflow.com/questions/10898022/difference-between-counting-and-binary-semaphores

Related questions

0 votes
0 votes
1 answer
3
ajayraho asked Oct 23, 2022
876 views
What is the significance of infinite loop that is written in every example of process synchronisation? What would happen if there wasn't any infinite loop?