Skip to content
Official PYQ · 2012

GATE CS 2012 Q32 — Concurrency and Synchronization

Explain with AI

Fetch_And_Add(X,i) is an atomic Read-Modify-Write instruction that reads the value of memory location XX, increments it by the value ii, and returns the old value of XX. It is used in the pseudocode shown below to implement a busy-wait lock. LL is an unsigned integer shared variable initialized to 00. The value of 00 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

Choose one option
View worked solution

Answer: B

To analyze the behavior of the lock implementation, let us trace the execution with two processes, P1P_1 and P2P_2, where the shared variable LL is initially 00 (lock is available):

  1. P1P_1 attempts to acquire the lock:
    • P1P_1 executes Fetch_And_Add(L, 1). This atomically reads the old value 00, increments LL to 11, and returns 00.
    • Since the returned value is 00, the while loop condition is false. P1P_1 successfully acquires the lock and enters the Critical Section (CS).
  2. P2P_2 attempts to acquire the lock while P1P_1 is in the CS:
    • P2P_2 executes Fetch_And_Add(L, 1). This reads the current value 11, increments LL to 22, and returns 11.
    • Since the returned value is 11 (non-zero), P2P_2 enters the loop body and is about to execute L = 1;.
  3. P1P_1 releases the lock:
    • P1P_1 finishes its CS and calls ReleaseLock(L), which sets L=0L = 0. The lock is now conceptually free.
  4. P2P_2 resumes execution:
    • P2P_2 now executes its pending loop body statement: L = 1;.
    • This overwrites the value of LL back to 11.

At this point, no process is in the Critical Section, meaning the lock is actually available. However, because L=1L = 1, any subsequent call to AcquireLock(L) by any process will read a non-zero value and get stuck in the busy-wait loop. Thus, the implementation fails because LL can take on a non-zero value when the lock is actually available.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Concurrency and Synchronization questions