GATE / CS ARCHIVE

GATE CSE 2012 / QUESTION 32

Lost unlock in a fetch-and-add lock

Operating Systems · Synchronization & Concurrency · Full GATE CSE 2012 paper

GATE 2012, Q32 2 marks · MCQ
Report issue

Synchronization & Concurrency

Question 32, GATE 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. 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
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Suppose one process holds the lock with L=1. A waiter executes Fetch_And_Add, obtains old value 1 and changes L to 2, so it must execute the loop body. Before that body executes, the owner releases the lock by storing L=0. The waiter then executes its pending L=1 assignment, restoring a nonzero value even though nobody holds the lock. Subsequent tests keep failing and there need be no owner left to release it. Thus B identifies a failure even without arithmetic overflow.

Check: Atomicity protects the fetch-and-add operation itself, not the following plain assignment. The interleaving is: waiter atomically changes 1→2; owner changes 2→0; waiter changes 0→1. The last store overwrites the release and leaves no holder responsible for another release.

Original paper, page 7 · Answer key