IAE Academy

GATE 2022 CS Q.19: solution and answer

GATE 2022 · CSQ.19 · 1 mark · MCQ

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.

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

GATE 2022 CS question 19: A three-column table with headers T1, T2, T3.Tap to open full size
Figure from the GATE 2022 CS paper. It is part of the question.
Figure description

A three-column table with headers T1, T2, T3. T1: while(true) wait(S3); print("C"); signal(S2);. T2: while(true) wait(S1); print("B"); signal(S3);. T3: while(true) wait(S2); print("A"); signal(S1);.

  1. (A)

    S1 = 1; S2 = 1; S3 = 1

  2. (B)

    S1 = 1; S2 = 1; S3 = 0

  3. (C)

    S1 = 1; S2 = 0; S3 = 0

  4. (D)

    S1 = 0; S2 = 1; S3 = 1

Answer and solution

ANSWER

Option (C): .

Official answer: CSource: Official answer key, GATE 2022 CS (IIT Kharagpur)

  1. Each thread waits on one semaphore and signals another. (prints B) signals , which enables (prints C). signals , which enables (prints A). signals , which enables again. So the semaphores pass a single token round , which gives the output BCABCA....

  2. The output must begin with B, so at the start only may be able to pass its wait, and neither nor may be able to. That requires , and .

  3. Trace from . Only can pass wait(S_1), because and block the others. prints B and signals , giving . Now only can proceed.

  4. takes to 0, prints C and signals , giving . Now only can proceed. It takes to 0, prints A and signals , giving . The state is back at the start, so BCA repeats for ever, whatever the context-switch order.

  5. The other options fail. (A) enables all three threads, so A or C can be printed first. (B) enables and , so can print A before any B. (D) enables and but not , so the first letter is C or A, never B.

  6. Answer: (C).

KEY IDEA

Binary semaphores can pass a token around a cycle of threads. To force one fixed order, initialise exactly one semaphore to 1, the one the first thread in the order waits on, and set the rest to 0.

WATCH OUT FOR

Giving the starting semaphores of the other threads a value of 1 as well. Then several threads are enabled at once, and the context-switch order can print A or C before B.

From the GATE 2022 CS paper. Every question of this paper · Download the full paper · All 7 Synchronisation questions, with notes

More Synchronisation questions