Correct Answer - Option 3 :
Deadlock occurs if the consumer succeeds in acquiring semaphore s when the buffer is empty.
Explanation:
semaphore n = 0;
semaphore s = 1;
void producer()
{
1 while(true)
2 {
3 produce();
4 semWait(s);
5 addToBuffer();
6 semSignal(s);
7 semSignal(n);
}
}
|
void consumer()
{
1 while(true)
2 {
3 semWait(s);
4 semWait(n);
5 removeFromBuffer();
6 semSignal(s);
7 consume();
}
}
|
Method 1
- If consumer executes first and execute line number 1, 2, 3 and now after 3 it has been pre-empted and now producer start executing line number 1, 2 , 3 after line 3 producer will go into waiting because s is 0 it is decremented by consumer earlier, now we pre-empted producer.
- Now again consumer start executing from line 4 but it cannot execute further because n=0 and it will for n to become 1, now we pre-empted consumer process.
- Now we can see that both are waiting for each other, producer it waiting to become s=1 from
Consumer and consumer is waiting to become n=1 from producer.
- This is nothing but deadlock.
Method 2:
Consumer: 1, 2 3 |producer 1,2, 3,4 (waiting for s to become 1)| consumer : 4 (waiting for n to become 1 ) So both are in waiting state so deadlock .
Hence option 3 is the correct answer.