GATE / CS ARCHIVE

GATE CSE 2002 / QUESTION 18(b)(i)

Test-and-set lock entry and exit

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

GATE 2002, Q18(b)(i) Descriptive
Report issue

Synchronization & Concurrency

Question 18(b)(i), GATE 2002: Atomic TEST_AND_SET(int*x) performs A1:y=*x; A2:*x=1; A3:return y. Shared mutex initially 0. Entry/exit templates: void enter_cs(){while(blank);} void leave_cs(){blank;} Original18(b)(i): Fill the while condition in enter_cs(){while(blank);} and the statement in leave_cs(){blank;} using this instruction.
Question 18(b)(i), GATE 2002: Atomic TEST_AND_SET(int*x) performs A1:y=*x; A2:*x=1; A3:return y. Shared mutex initially 0. Entry/exit templates: void enter_cs(){while(blank);} void leave_cs(){blank;} Original18(b)(i): Fill the while condition in enter_cs(){while(blank);} and the statement in leave_cs(){blank;} using this instruction.
Question 18(b)(i), GATE 2002: Atomic TEST_AND_SET(int*x) performs A1:y=*x; A2:*x=1; A3:return y. Shared mutex initially 0. Entry/exit templates: void enter_cs(){while(blank);} void leave_cs(){blank;} Original18(b)(i): Fill the while condition in enter_cs(){while(blank);} and the statement in leave_cs(){blank;} using this instruction.
Question 18(b)(i), GATE 2002: Atomic TEST_AND_SET(int*x) performs A1:y=*x; A2:*x=1; A3:return y. Shared mutex initially 0. Entry/exit templates: void enter_cs(){while(blank);} void leave_cs(){blank;} Original18(b)(i): Fill the while condition in enter_cs(){while(blank);} and the statement in leave_cs(){blank;} using this instruction.
Tap to enlarge
Answer & solution

Answer: enter_cs: while (TEST_AND_SET(&mutex)) { } ; leave_cs: mutex=0; (no official key was published)

Use the shared lock variable mutex, initially zero:
void enter_cs(void) { while (TEST_AND_SET(&mutex)) { } }
void leave_cs(void) { mutex = 0; }
TEST_AND_SET atomically returns the old value and writes one. Exactly one contender observing the unlocked zero receives zero and leaves the loop; later contenders receive one and keep spinning. Releasing the lock restores zero for a future acquisition. This is pseudocode for the given atomic primitive and a shared lock, not a claim that an ordinary non-atomic C integer and a handwritten function implement modern concurrent-C synchronization. The source's hyphenated function names are rendered with underscores to make the names valid C identifiers.

Original paper, page 9