GATE / CS ARCHIVE

GATE CSE 1999 / QUESTION 20(a)

Implement a test-and-set spinlock

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

GATE 1999, Q20(a) 2 marks · Descriptive
Report issue

Synchronization & Concurrency

Question 20(a), GATE 1999: TSET register,flag atomically copies flag into register and sets flag=1. Give entry and exit pseudocode for a critical region.
Question 20(a), GATE 1999: TSET register,flag atomically copies flag into register and sets flag=1. Give entry and exit pseudocode for a critical region.
Tap to enlarge
Answer & solution

Answer: Spin until TSET returns 0; release by setting flag to 0. (no official key was published)

Initialize a shared flag to 0 before any competing process starts. Each process uses its own register r.

shared flag := 0

entry:
  repeat
    TSET r, flag
  until r = 0

critical_region()

exit:
  flag := 0

TSET must run on every retry; reading a stale r in a spin loop would never acquire the lock. When flag=0, exactly one atomic TSET can observe that 0 and simultaneously change flag to 1. That process enters; all later tests obtain 1 and continue waiting. Only the owner clears the flag on exit. This establishes mutual exclusion, assuming atomic release stores and the abstract sequentially consistent memory model of the question. Real machines additionally require appropriate acquire/release memory ordering. The scheme busy-waits and does not by itself guarantee bounded waiting or freedom from starvation.

Original paper, page 9