• edited by
102 views
0 0 votes

Consider a multi-threaded program with two threads T1 and T2. The threads share two semaphores: S1 and S2 both initialised to $1$. The threads also share a global variable $x$ (initialized to $0$ ). The threads execute the code shown below.
$$
\begin{array}{|c|c|}
\hline
\text{Thread T1:} & \text{Thread T2:} \\
\text{wait}(S1);  & \text{wait}(S2); \\
x = x + 1;        & \text{wait}(S1); \\
\text{print}(x);  & x = x + 2; \\
\text{signal}(S1);& \text{print}(x); \\
                  & \text{signal}(S2); \\
\hline
\end{array}
$$
Which of the following outcomes is/are possible when threads execute concurrently?

  1. T1 runs first and prints $1$, T2 runs next and prints $3$.
  2. T2 runs first and prints $2$, T1 runs next and prints $3$.
  3. T1 runs first and prints $1$, T2 does not print anything (deadlock)
  4. T2 runs first and prints $2$, T1 does not print anything (deadlock)

1 Answer

0 0 votes

Answer: A and D are possible.

Given :-

  • S1 and S2 start at 1.

  • T1 only waits/signals S1. It does wait(S1) → x = x+1 → print(1) → signal(S1).

  • T2 does wait(S2) → wait(S1) → x = x+2 → print(x) → signal(S2) — note: T2 never signals S1.

Two possibilities :-

  1. T1 runs first: T1 acquires S1, does x = 1, prints 1, signals S1. Then T2 can acquire S2 and S1, do x = 3, print 3, signal S2. → Outcome A (1 then 3) is possible.

  2. T2 runs first: T2 acquires S2 and S1, does x = 2, prints 2, signals S2 but does not release S1. Now T1 blocks on wait(S1) forever → T1 never prints. → Outcome D (2 then deadlock / T1 prints nothing) is possible.

Outcomes B and C are not possible because T2 never signals S1, so T1 cannot run after T2 has acquired S1.

Answer:
Position:
Show:

Related questions

0 0 votes
1 1 answer
177
177 views
GO Classes asked Sep 15, 2025
177 views
Consider the following two threads, to be run concurrently in a shared memory (all variables are shared between the two threads):Assume a single-processor system, that lo...
1 1 vote
2 2 answers
272
272 views
GO Classes asked Sep 15, 2025
272 views
Consider the following two threads, to be run concurrently in a shared memory (all variables are shared between the two threads):Assume a single-processor system, that lo...
10 10 votes
2 2 answers
315
315 views
GO Classes asked Sep 15, 2025
315 views
Assume a system with following specification:1. A two set associative TLB2. A TLB with 8 total entries3. $2^{8}$ byte page size4. $2^{16}$ bytes of virtual memoryWhich of...
2 2 votes
1 1 answer
479
479 views
GO Classes asked Sep 15, 2025
479 views
Void main() { int a = 0; for (int i = 0; i < 4; i++) { if (fork() == 0) { a++; return ; } else { a++; ...