Question
Consider a multi-threaded program with two threads T1 and T2. The threads share two semaphores: s1 (initialized to 1) and s2 (initialized to 0). The threads also share a global variable x (initialized to 0). The threads execute the code shown below.
// code of T1 // code of T2
wait(s1); wait(s1);
x = x+1; x = x+1;
print(x); print(x);
wait(s2); signal(s2);
signal(s1); signal(s1);
Which of the following outcomes is/are possible when threads T1 and T2 execute concurrently?
Official answer and solution
- Official answer
- B and C
- From
- Official GATE 2024 answer key
Solution
Trace both possible interleavings depending on whether T1 or T2 acquires semaphore s1 first.
Since s1 = 1 acts as a mutex protecting the start of both threads, either T1 or T2 acquires s1 first:
- Case 1: T1 acquires
s1first (s1becomes 0):- T1 increments
xto1and prints1. - T1 then executes
wait(s2). Becauses2 = 0, T1 blocks ons2while still holdings1. - T2 executes
wait(s1)and blocks becauses1 = 0. Neither thread can proceed (deadlock). - This yields outcome (C) (and makes (A) impossible).
- T1 increments
- Case 2: T2 acquires
s1first (s1becomes 0):- T2 increments
xto1, prints1, executessignal(s2)(s2becomes 1), and executessignal(s1)(s1becomes 1). - T1 then acquires
s1, incrementsxto2, prints2, passeswait(s2)(sinces2 = 1), and releasess1. - This yields outcome (B) (and makes (D) impossible).
- T2 increments
Options (B), (C)
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2024 Computer Science and Information Technology - Set 2 (CS2)
- Question
- 46 of 65
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.