Consider a multi-threaded program with two threads and . The threads share two semaphores: (initialized to ) and (initialized to ). The threads also share a global variable (initialized to ). The threads execute the code shown below.
//code of T 1 wait (s1); x = x+1; print (x); wait (s2); signal(s1);
// code of T2 wait (s1); x= x+1; print (x) ; signal (s2); signal (s1);
Which of the following outcomes is/are possible when threads and execute concurrently?
View worked solution
Answer: B;C
To find the possible outcomes, let us trace the execution of threads and under different scheduling scenarios.
Initial State:
, , and .
Scenario 1: Thread starts first
- executes
wait(s1): Since , it decrements to , and proceeds. - executes
x = x + 1: becomes . - executes
print(x): Prints . - executes
wait(s2): Since , blocks and goes to the waiting queue of . - Now, attempts to run and executes
wait(s1): Since , blocks and goes to the waiting queue of .
At this point, is blocked waiting for (which only can signal), and is blocked waiting for (which only can signal). This is a deadlock.
Outcome: prints , and does not print anything due to deadlock. (Matches Option C)
Scenario 2: Thread starts first
- executes
wait(s1): Since , it decrements to , and proceeds. - executes
x = x + 1: becomes . - executes
print(x): Prints . - executes
signal(s2): becomes . - executes
signal(s1): becomes . finishes execution. - Now, runs and executes
wait(s1): Since , it decrements to , and proceeds. - executes
x = x + 1: becomes . - executes
print(x): Prints . - executes
wait(s2): Since , it decrements to , and proceeds without blocking. - executes
signal(s1): becomes . finishes execution.
Outcome: prints , and then prints . (Matches Option B)
Conclusion
- Option A is incorrect because if runs first, it inevitably blocks on
wait(s2)before can execute. - Option D is incorrect because if runs first, it signals both semaphores, allowing to complete successfully without any deadlock.
Thus, the correct options are B and C.
Free practice · Your answers on this page are not saved.
