Skip to content
Related Articles

Related Articles

Improve Article

GATE | GATE CS 2012 | Question 30

  • Difficulty Level : Medium
  • Last Updated : 06 Dec, 2018

Fetch_And_Add(X,i) is an atomic Read-Modify-Write instruction that reads the value of memory location X, increments it by the value i, and returns the old value of X. It is used in the pseudocode shown below to implement a busy-wait lock. L is an unsigned integer shared variable initialized to 0. The value of 0 corresponds to lock being available, while any non-zero value corresponds to the lock being not available.

  AcquireLock(L){
         while (Fetch_And_Add(L,1))
               L = 1;
   }
  ReleaseLock(L){
         L = 0;
   }

This implementation
(A) fails as L can overflow
(B) fails as L can take on a non-zero value when the lock is actually available
(C) works correctly but may starve some processes
(D) works correctly without starvation


Answer: (B)

Explanation: Take closer look the below while loop.

Attention reader! Don’t stop learning now.  Practice GATE exam well before the actual exam with the subject-wise and overall quizzes available in GATE Test Series Course.

Learn all GATE CS concepts with Free Live Classes on our youtube channel.

     while (Fetch_And_Add(L,1))
               L = 1;  // A waiting process 
                       // can be here just after 
                       // the lock is released, 
                       // and can make L = 1.

Consider a situation where a process has just released the lock and made L = 0. Let there be one more process waiting for the lock, means executing the AcquireLock() function. Just after the L was made 0, let the waiting processes executed the line L = 1. Now, the lock is available and L = 1. Since L is 1, the waiting process (and any other future coming processes) can not come out of the while loop.



The above problem can be resolved by changing the AcuireLock() to following.

  AcquireLock(L){
         while (Fetch_And_Add(L,1))
         { // Do Nothing }
   }

Overflow can occur only when larger number of processes than size of ‘int’ execute the check condition of while loop but not L = 1, i.e., preemption required.
But when L is 1, the process repeats in the while loop- there is no overflow because after each increment to L, L is again made equal to 1.
Option (b) is best choice over option (a).

Source :  http://www.geeksforgeeks.org/operating-systems-set-17/


Quiz of this Question

My Personal Notes arrow_drop_up
Recommended Articles
Page :