GATE / CS ARCHIVE

GATE CSE 2024 SET 2 / QUESTION 46

A semaphore ordering that can deadlock

Operating Systems · Deadlocks · Full GATE CSE 2024 Set 2 paper

GATE 2024 Set 2, Q46 2 marks · MSQ
Report issue

Deadlocks

Question 46, GATE 2024: Threads share s1=1,s2=0,x=0. T1: wait(s1); x++; print(x); wait(s2); signal(s1). T2: wait(s1); x++; print(x); signal(s2); signal(s1). Possible outcomes? A T1 prints 1 then T2 prints 2; B T2 prints 1 then T1 prints 2; C T1 prints 1 then deadlock without T2 printing; D T2 prints 1 then deadlock without T1 printing.
Tap to enlarge
Select all that apply
Answer & solution

Official answer: B, C

Approach: Branch on which thread acquires s1 first, since this excludes the other thread from its increment.

1. Derivation. The first successful wait(s1) excludes the other thread. If T1 acquires it first, T1 increments and prints 1, then blocks on initially zero s2 while still holding s1; T2 cannot reach its signal(s2), so this deadlocks, giving C. If T2 acquires first, it prints 1 and signals s2 and s1. T1 can then acquire s1, print2, consume s2, and finish, giving B. Thus B, C.

2. Explanation and checks. In the T1-first branch the wait-for chain is T1 waiting for s2, which only T2 signals; T2 waits for s1, which T1 will not signal until its s2 wait finishes. In the T2-first branch signal(s2) either stores a permit or satisfies a waiting thread, so T1’s later wait(s2) cannot deadlock. The mutual exclusion around x prevents a lost increment, but it does not prevent the circular wait caused by the semaphore ordering.

Original paper, page 32 · Answer key