Question

Consider the following threads, T1, T2, and T3 executing on a single processor, synchronized using three binary semaphore variables, S1, S2, and S3, operated upon using standard wait() and signal(). The threads can be context switched in any order and at any time.

/* Thread T1 */
while(true){
    wait(S3);
    print("C");
    signal(S2);
}

/* Thread T2 */
while(true){
    wait(S1);
    print("B");
    signal(S3);
}

/* Thread T3 */
while(true){
    wait(S2);
    print("A");
    signal(S1);
}

Which initialization of the semaphores would print the sequence BCABCABCA....?

Choose one option
Official answer and solution
Official answer
C
From
Official GATE 2022 answer key

Solution

Trace the semaphore dependencies to establish the required cyclic print sequence B -> C -> A -> B.

To print the sequence B,C,A,B,C,A,…B, C, A, B, C, A, \dots:

  1. The very first character to be printed must be 'B'. In the code, thread T2T_2 prints 'B' after wait(S1). Hence, T2T_2 must be enabled initially, requiring S1=1S_1 = 1.
  2. To ensure that neither 'C' nor 'A' is printed before 'B', threads T1T_1 (which waits on S3S_3) and T3T_3 (which waits on S2S_2) must be blocked initially. Hence, S2=0S_2 = 0 and S3=0S_3 = 0.
  3. Once T2T_2 executes, it prints 'B' and signals S3S_3, unblocking T1T_1.
  4. T1T_1 prints 'C' and signals S2S_2, unblocking T3T_3.
  5. T3T_3 prints 'A' and signals S1S_1, unblocking T2T_2 to print the next 'B'.

Thus, the unique initial values that strictly enforce the sequence are S1=1,S2=0,S3=0S_1 = 1, S_2 = 0, S_3 = 0.

Final answer

Option (C)

Common trap

Initializing multiple semaphores to 1, which introduces race conditions allowing 'A' or 'C' to print first.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2022 Computer Science and Information Technology (CS)
Question
19 of 65
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.