GATE / CS ARCHIVE

GATE CSE 2021 SET 1 / QUESTION 46

GATE CSE 2021 Set 1 Q46

Operating Systems · Synchronization & Concurrency · Full GATE CSE 2021 Set 1 paper

GATE 2021 Set 1, Q46 2 marks · MSQ
Report issue

Synchronization & Concurrency

Question 46, GATE 2021: Shared counter=0 and counting semaphore S=5. Five threads concurrently execute parop(){wait(S); wait(S); counter++; signal(S); signal(S);} The increment is explicitly non-atomic. Select possible outcomes: A counter=5 after all complete; B counter=1 after all complete; C counter=0 after all complete; D all five threads deadlock.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: A; B; D

Serially completing all five operations gives counter=5, proving A. For B, let one thread acquire two permits and read counter=0, then pause before writing. The other four can each acquire two of the remaining three permits, increment and finish sequentially. Finally the paused thread writes its stale result 1 and finishes. C cannot occur after successful completion: every write is a nonnegative value read plus one, so the final write is at least 1. For D, let each of the five threads acquire its first permit before any acquires a second. All then block on the second wait with no permit left and none able to signal. These are pseudocode read-modify-write interleavings, as explicitly assumed.

The semaphore limits simultaneous holders of permits but does not provide mutual exclusion for counter++: two threads can each hold two permits out of five. For final value 1, the crucial schedule is a delayed stale write from the first thread after the other four have successively completed. For deadlock, no thread reaches its first signal because every thread is stuck on its second wait. Replacing the two waits by one atomic acquisition of two permits would remove that particular hold-and-wait pattern, but that is not the given code.

Original paper, page 37 · Answer key