Skip to content
Official PYQ · 2021

GATE CS 2021 Set 1 Q46 — Concurrency and Synchronization

Explain with AI

Consider the following pseudocode, where S\textsf{S} is a semaphore initialized to 55 in line #2\#2 and counter\textsf{counter} is a shared variable initialized to 00 in line #1\#1. Assume that the increment operation in line #7\#7 is not\textit{not} atomic.

1.  int counter = 0;
2.  Semaphore S = init(5);
3.  void parop(void)
4.  {
5.         wait(S);
6.         wait(S);
7.         counter++;
8.         signal(S);
9.         signal(S);
10.  }

If five threads execute the function parop\textsf{parop} concurrently, which of the following program behavior(s) is/are possible?

Select all correct options
View worked solution

Answer: A;B;D

Let us analyze each option by tracing the concurrent execution of the 5 threads:

  • Option D is possible (Deadlock): Initially, S=5S = 5. Suppose all 5 threads execute their first wait(S) statement (line 5) concurrently. Each thread successfully decrements SS by 1, making S=0S = 0. Now, all 5 threads reach line 6 and attempt to execute the second wait(S). Since S=0S = 0, all of them block indefinitely, resulting in a deadlock.
  • Option A is possible (Value of 5): If the threads execute sequentially one after another without any interleaved context switches during the non-atomic counter++ operation, each thread successfully increments the counter by 1. The final value of counter will be 55.
  • Option B is possible (Value of 1): Since the counter++ operation is non-atomic, it consists of three steps: Read, Increment, and Write.
    1. Thread T1T_1 enters the critical section, reads counter = 0 into its local register, and is preempted before writing.
    2. Since T1T_1 holds 2 units of the semaphore, S=3S = 3. The remaining threads T2,T3,T4,T5T_2, T_3, T_4, T_5 can still execute sequentially. They run to completion, updating counter to 44.
    3. Thread T1T_1 resumes, increments its local register value from 00 to 11, and writes 11 back to counter.
    Thus, the final value of counter becomes 11.
  • Option C is impossible (Value of 0): If all threads successfully complete their execution, at least one write operation to counter must occur. Since counter starts at 00 and any write operation writes a value of at least read_value+1≥1\text{read\_value} + 1 \ge 1, the final value of counter can never be 00.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Concurrency and Synchronization questions