Each of a set of \(n\) processes executes the following code using two…
2020
Each of a set of \(n\) processes executes the following code using two semaphores \(a\) and \(b\) initialized to 1 and 0, respectively. Assume that \(count \) is a shared variable initialized to 0 and not used in CODE SECTION \(P\).
\(\begin{array}{|c|} \hline \textbf{CODE SECTION P} \\ \hline \end{array}\)
wait(a); count=count+1;
if (count==n) signal (b);
signal (a); wait (b) ; signal (b);
\(\begin{array}{|c|} \hline \textbf{CODE SECTION Q} \\ \hline \end{array}\)
What does the code achieve ?
- A.
It ensures that no process executes
\(CODE \ SECTION \ Q\)before every process has finished\(CODE \ SECTION \ P\). - B.
It ensures that two processes are in
\(CODE \ SECTION \ Q\)at any time. - C.
It ensures that all processes execute
\(CODE \ SECTION \ P\)mutually exclusively. - D.
It ensures that at most
\(n−1\)processes are in\(CODE \ SECTION \ P\)at any time.
Attempted by 136 students.
Show answer & explanation
Correct answer: A
Answer: The code implements a barrier that prevents any process from entering CODE SECTION Q until all n processes have finished CODE SECTION P.
Step 1: wait(a) and signal(a) make the increment of the shared count mutually exclusive, so count correctly counts how many processes have finished P.
Step 2: When the nth process increments count, it executes signal(b). Semaphore b was initialized to 0, so all processes that do wait(b) before this signal are blocked.
Step 3: After b is signaled once, each waiting process does wait(b) then immediately does signal(b). This passes a "token" to the next waiting process, letting all n processes eventually proceed into CODE SECTION Q.
Consequence: No process can enter CODE SECTION Q until count == n (i.e., until every process has completed CODE SECTION P). Note that CODE SECTION P itself is not made mutually exclusive by this code—only the count update is protected.