Fetch_And_Add(X, i) is an atomic Read-Modify-Write instruction that reads the…

2012

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.

Context: It is used in the pseudocode below to implement a busy-wait lock. L is an unsigned integer shared variable initialized to 0. A value of 0 means the lock is available; any non-zero value means it is not available.

AcquireLock(L)

ReleaseLock(L)

while (Fetch_And_Add(L, 1))

{

    L = 1;

    L = 0;

}

}

  1. A.

    fails as L can overflow

  2. B.

    fails as L can take on a non-zero value when the lock is actually available

  3. C.

    works correctly but may starve some processes

  4. D.

    works correctly without starvation

Attempted by 51 students.

Show answer & explanation

Correct answer: B

The Fetch_And_Add instruction returns the old value of L before incrementing. If a process reads 0, it enters the loop but resets L to 0 immediately. This allows another process to read 0 and enter concurrently, violating mutual exclusion.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir