Skip to main content

GATE CSE 2024Operating System › Process Synchronization & ConcurrencyVerified

GATE CSE 2024 PYQ: ​​​​​Consider a multi-threaded program with two threads T 1 \mathrm{T} 1 T 1 and T 2 \mathrm{T} 2 T 2 . The…

​​​​​Consider a multi-threaded program with two threads T1\mathrm{T} 1 and T2\mathrm{T} 2. The threads share two semaphores: s1s1 (initialized to 1) and s2s2 (initialized to 0). The threads also share a global variable x\mathrm{x} (initialized to 0). The threads execute the code shown below.

  1. //code of T 1
  2. wait (s1);
  3. x = x+1;
  4. print (x);
  5. wait (s2);
  6. signal(s1);
  1. // code of T2
  2. wait (s1);
  3. x= x+1;
  4. print (x) ;
  5. signal (s2);
  6. signal (s1);


Which of the following outcomes is/are possible when threads T1\mathrm{T} 1 and T2\mathrm{T} 2 execute concurrently?

  1. A
    T1\mathrm{T} 1 runs first and prints 1, T21, \mathrm{~T} 2 runs next and prints 2
  2. B
    T2\mathrm{T} 2 runs first and prints 1, T11, \mathrm{~T} 1 runs next and prints 2
    Correct answer
  3. C
    T1\text{T1} runs first and prints 1,T 21, \text{T 2} does not print anything (deadlock)
    Correct answer
  4. D
    T2\mathrm{T} 2 runs first and prints 1, T11, \mathrm{~T} 1 does not print anything (deadlock)

Answer

(B, C) T 2 \mathrm{T} 2 T 2 runs first and prints 1 , T 1 1, \mathrm{~T} 1 1 , T 1 runs next and prints 2 2 2; T1 \text{T1} T1 runs first and prints 1 , T 2 1, \text{T 2} 1 , T 2 does not print anything (deadlock)

Approach

Model each semaphore operation according to standard wait/signal semantics. The first wait(s1) acts as a mutex: only one thread can enter the critical section that increments and prints x. Then trace both possible first-thread wins and check whether the other thread can ever complete.

Only outcomes B and C can occur. The first wait(s1) acts as a mutex, so whichever thread acquires s1 first determines the outcome. If T1 wins, it prints 1 and then deadlocks on wait(s2) while holding s1, so T2 prints nothing (C). If T2 wins, it prints 1, signals s2 and s1, allowing T1 to print 2 (B). Options A and D are impossible.

Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.