Consider three processes , and running identical code, as shown in the pseudocode below. and are two binary semaphores initialized to and , respectively. is a shared variable initialized to . Each line in the pseudocode is executed atomically.
Pseudocode of P1, P2, and P3
Wait(A);
Print(*);
X = X+1;
If (X == 2)
{
Print($);
Signal(B);
}
Signal(A);
Wait(B);
Print(#);
Signal(B);Assume that any of the three processes can start to execute first and context switching can happen between these processes at any arbitrary time and in any arbitrary order.
Which of the following patterns is/are possible to be generated as an outcome of the execution of these three processes?
View worked solution
Answer: A;B;C
Let us analyze the execution of the three processes step-by-step with the initial values , , and :
- First process (say ) enters the critical section:
- Prints
*, increments to . - Since , it skips the
ifblock, signals (), and blocks atWait(B).
- Prints
- Second process (say ) enters the critical section:
- Prints
*, increments to . - Since , it prints
$, signals (), and then signals (). - At this point, the output prefix is strictly
**$.
- Prints
Since cannot enter the critical section until signals (which happens only after printing $</code>), the third <code>*</code> cannot be printed before <code>$. Thus, Option D (***$###) is impossible.
After signals and :
- can enter the critical section to print the third
*. - and can proceed past
Wait(B)to print#. - can only print its
#after it has printed its*. Thus, at most two#s (from and ) can be printed before the third*.
This allows the third * to appear in any of the following positions relative to the #s:
- Before any
#:**$*###(Option A) - After one
#:**$#*##(Option B) - After two
#s:**$##*#(Option C)
Free practice · Your answers on this page are not saved.
