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
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 T1 and T2 execute concurrently?
Answer
(B), (C)
Explanation
Only one thread at a time can be between wait(s1) and signal(s1), and s2 starts at 0.
- If
T2getss1first, it prints 1, and itssignal(s2)andsignal(s1)never block.T1then enters, prints 2, findss2at 1 and finishes. So (B) is possible, and (D) is not:T1cannot stay blocked. - If
T1getss1first, it prints 1 and blocks onwait(s2)while still holdings1. OnlyT2could signals2, but it is stuck atwait(s1), so both wait forever andT2prints nothing. So (C) is possible and (A) is not.
Answer: B, C