Each of a set of processes executes the following code using two semaphores and initialized to and , respectively. Assume that is a shared variable initialized to and not used in CODE SECTION P.
wait(a); count=count+1; if (count==n) signal (b); signal (a); wait (b) ; signal (b);
What does the code achieve?
View worked solution
Answer: A
This code implements a classic Barrier Synchronization mechanism. Let us analyze the execution step-by-step:
1. Initial State
- Semaphore (used for mutual exclusion when updating the shared variable
count). - Semaphore (used to block processes until all of them reach the barrier).
count = 0.
2. Execution of the First Processes
When any of the first processes finish CODE SECTION P and enter the synchronization block:
- They acquire the lock via
wait(a). - They increment
count. Sincecount < n, the conditionif (count == n)is false, so they do not signal . - They release the lock via
signal(a). - They execute
wait(b). Since , these processes get blocked here.
3. Arrival of the -th Process
When the -th process finishes CODE SECTION P and enters the synchronization block:
- It acquires lock , increments
countto . - Since
count == n, it executessignal(b), which increments to . - It releases lock via
signal(a). - It executes
wait(b)(which succeeds, decrementing back to ) and immediately executessignal(b)(incrementing back to ). - It then proceeds to CODE SECTION Q.
4. Cascading Wake-up
The signal(b) executed by the -th process wakes up one of the blocked processes waiting at wait(b). That awakened process then executes signal(b), which wakes up the next process, and so on. This cascading effect ensures all processes are unblocked and can proceed to CODE SECTION Q.
Conclusion
No process can enter CODE SECTION Q until the -th process has finished CODE SECTION P and signaled . Thus, it ensures that no process executes CODE SECTION Q before every process has finished CODE SECTION P.
Therefore, Option A is the correct choice.
Free practice · Your answers on this page are not saved.
