The following program solves producer/consumer problem with limited buffer of si
ID: 3710082 • Letter: T
Question
The following program solves producer/consumer problem with limited buffer of size 3:
/* program producer_consumer*/
Const int buffer_size= 3
Semaphore lock =1;
Semaphore n=-1;
Semaphore f= buffer_size;
Voide procedure()
{
While (true)
{
Produce();
SemWait(f);
SemWait(lock);
append;
semSignal(lock);
semSignal(n)
}
}
Voide consumer()
{
While (true)
{
SemWait(n);
SemWait(lock);
take;
semSignal(lock);
semSignal(f)
}
}
void main()
{
Parbegin (producer and consumer)
}
1. Try to trace the above program in the following sequence: - producer starts first and produces two items then the consumer can start to consume one item.
2. Is there any problem in part 1? if there is, show what this problem and try to solve it.
Explanation / Answer
Solution:
1)
If the producer is starting first and producing 2 items then the consumer is consuming one item at a time.
Producer starts first
f= 3, buffer_size = 3, lock= 1, n= -1
after producer is executed the values will become
f= 2, buffer_size = 3, lock= 1, n= 0
after producing the second item
f= 1, buffer_size = 3, lock= 1, n= 1
Now consumer is initiated
f= 2, buffer_size = 3, lock= 1, n= 0
Now consumer cannot enter the buffer and access the item while there is still inside
2)
Yes, the problem is that if producer is premepted just after the semWait(f), then the consumer will enter the critical section and would find nothing in the buffer.
One more is that the consumer cannot enter the buffer when there is still one item in there.
This problem should be resolved by swapping the semWait(lock) and semWait(g) and setting n to 0 at the very start.
I hope this helps if you find any problem. Please comment below. Don't forget to give a thumbs up if you liked it. :)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.