Question
Each of a set of processes executes the following code using two semaphores and initialized to 1 and 0, respectively. Assume that count is a shared variable initialized to 0 and not used in CODE SECTION P.
CODE SECTION P
wait(a);
count = count + 1;
if (count == n)
signal(b);
signal(a);
wait(b);
signal(b);
CODE SECTION Q
What does the code achieve?
Official answer and solution
- Official answer
- A
- From
- Official GATE 2020 answer key
Solution
Trace semaphore operations to recognize the reusable barrier synchronization pattern.
Initial state:
- Semaphore (provides mutual exclusion for updating
count). - Semaphore (blocks processes until all arrive).
- Shared variable
count = 0.
Execution trace:
- As each of the first processes finishes CODE SECTION P, it enters the critical section protected by , increments
count, checksif (count == n)(which is false), releases , and executeswait(b). - Since , all first processes block at
wait(b). - When the -th process finishes CODE SECTION P, it enters the critical section, increments
countto , satisfiesif (count == n), and executessignal(b), making . - It then releases , executes
wait(b)(decrementing back to 0), immediately executessignal(b)(incrementing back to 1 for the next waiting process), and enters CODE SECTION Q. - This turnstile allows each waiting process to unblock one after another and proceed to CODE SECTION Q.
Conclusion:
- No process can pass
wait(b)and execute CODE SECTION Q until the -th process executessignal(b), which happens only after all processes have finished CODE SECTION P. - Hence, the code guarantees that no process executes CODE SECTION Q before every process has finished CODE SECTION P.
Final answer
A
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2020 Computer Science and Information Technology (CS)
- Question
- 44 of 65, printed as CS Q.34
- 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.