edited by
27,755 views
104 votes
104 votes

The atomic fetch-and-set $x, y$ instruction unconditionally sets the memory location $x$ to $1$ and fetches the old value of $x$ in $y$ without allowing any intervening access to the memory location $x$. Consider the following implementation of $P$ and $V$ functions on a binary semaphore $S$.

void P (binary_semaphore *s) { 
    unsigned y; 
    unsigned *x = &(s->value); 
    do { 
        fetch-and-set x, y; 
    } while (y); 
}

void V (binary_semaphore *s) { 
    S->value = 0; 
} 

Which one of the following is true? 

  1. The implementation may not work if context switching is disabled in $P$ 
  2. Instead of using fetch-and –set, a pair of normal load/store can be used 
  3. The implementation of $V$ is wrong
  4. The code does not implement a binary semaphore
edited by

6 Answers

0 votes
0 votes

Say, old value of x is 0 and not 1, bcz if old value of x=1 then why ques says that fetches old value of x and set x=1.
So, suppose x=0 initially.

Code for P:
----------------------------------------
Line 1: void P (binary_semaphore *s) {
Line 2: unsigned y;
Line 3: unsigned *x = &(s->value);
Line 4: do {
Line 5: fetch-and-set x, y;
Line 6: } while (y);
Line 7: }

Code for V:
----------------------------------------
Line 8: void V (binary_semaphore *s) {
Line 9: S->value = 0;
Line 10: }

So, since given that Context switching disabled in function P, so lines from 1 to 7 will execute without any pre-emption.

So, suppose a process P1 came, execute lines 1 to 5, now at line 5 it set x=1 and fetch y=0(bcz old value of x=0), and now it execute line 6 (while(0))--->false. 
Suppose this process is inside Critical section. 

Now suppose process P2 came, and it fetches value of y=1(bcz when process p1 execute fetch-and-set it sets x=1). So, now process P2 stuck in while loop-> while(1)-----> busy waiting.

Now, suppose P1 process execute its V code and make S.value=0.
Now, control came back to process P2. So now P2 execute line 5.
Now, key thing to note here is that->

fetches the old value of x in y without allowing any intervening access to the memory location x.
bcz, x contains memory location which contains S->value, and since memory access not allowed hence x contains old value which was 1 (when P2 first time executed fetch-and-set and set x=1)
so, it means even there is no one in Crirical section, still P2 is in busy waiting.

So, context switching is must in P.

Answer:

Related questions