Process A |
Process B |
1. block(); |
|
|
1. print "B" |
|
2. wakeup(A); |
2. print "A" |
|
3. wakeup(B); |
|
|
3. block(); (end of process B) |
1. block(); (process A is executed again) |
|
In this scenario, process $B$ is blocked and is waiting for process $A$ to wakeup (as wakeup(B) is performed only by process $A$) and process $A$ is blocked and is waiting for process $B$ to wakeup- Deadlock (none of the process proceeds).
Correction in the code as per intended behaviour( alternately printing names) two binary semaphores say $X, Y$ can be used, with initial values:
$X=1, Y=1 $
void A()
{
while(1) {
wait(X);
printf("A");
signal(Y);
}
}
|
void B()
{
while(1) {
wait(Y);
printf("B");
signal(X);
}
}
|
Either the process $A$ can start first in which the printed sequence will be $ABABA....$or process $B$ can start first in which the printed sequence will be $BABAB....$
This is wrong as there can be sequences ABB or BAA( not intended behaviour)
Process A |
Process B |
wait(X); |
|
print "A" |
|
|
wait(Y); |
|
print "B" |
signal(Y); |
|
|
wait(Y); (process B executes again) |
|
print "B" (sequence printed is $ABB$) |
So, semaphore initialization should be either $X=0, Y=1 $ or $ X=1, Y=0$