Skip to main content

GATE CSE 2021Operating System › Process Synchronization & ConcurrencyVerified

GATE CSE 2021 PYQ: Consider the following pseudocode, where S \textsf{S} S is a semaphore initialized to 5 5 5 in line # 2 \#2…

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

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

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

  1. A
    The value of counter\textsf{counter} is 5 after all the threads successfully complete the execution of parop\textsf{parop}
    Correct answer
  2. B
    The value of counter\textsf{counter} is 1 after all the threads successfully complete the execution of parop\textsf{parop}
    Correct answer
  3. C
    The value of counter\textsf{counter} is 0 after all the threads successfully complete the execution of parop\textsf{parop}
  4. D
    There is a deadlock involving all the threads
    Correct answer

Answer

(A, B, D) The value of counter \textsf{counter} counter is 5 5 5 after all the threads successfully complete the execution of parop \textsf{parop} parop; The value of counter \textsf{counter} counter is 1 1 1 after all the threads successfully complete the execution of parop \textsf{parop} parop; There is a deadlock involving all the threads

Approach

Analyze the counting semaphore as permitting at most two threads inside the critical section at once, while noting that counter++ is a non-atomic read-modify-write race. Then check each option by constructing valid schedules (or proving impossibility).

The semaphore S = 5 allows at most two threads in the critical section concurrently, but the non-atomic counter++ can cause lost updates. Valid schedules yield counter = 5 or counter = 1, counter = 0 is impossible, and all five threads can deadlock after consuming the five permits in their first wait operations.

Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.