Producer-consumer problem taken from Wikipedia:
semaphore mutex = 1
semaphore fillCount = 0
semaphore emptyCount = BUFFER_SIZE
procedure producer() {
while (true) {
item = produceItem()
down(emptyCount)
down(mutex)
putItemIntoBuffer(item)
up(mutex)
up(fillCount)
}
up(fillCount) //the consumer may not finish before the producer.
}
procedure consumer() {
while (true) {
down(fillCount)
down(mutex)
item = removeItemFromBuffer()
up(mutex)
up(emptyCount)
consumeItem(item)
}
}
My question - why does the producer have up(fillCount) //the consumer may not finish before the producer
after the while loop. When will the program get there and why is it needed?
There is a fixed size buffer and the producer produces items and enters them into the buffer. The consumer removes the items from the buffer and consumes them.
In the producer-consumer problem, we use three semaphore variables: Semaphore S: This semaphore variable is used to achieve mutual exclusion between processes. By using this variable, either Producer or Consumer will be allowed to use or access the shared buffer at a particular time.
To solve this problem, we need two counting semaphores – Full and Empty. “Full” keeps track of number of items in the buffer at any given time and “Empty” keeps track of number of unoccupied slots. When producer produces an item then the value of “empty” is reduced by 1 because one slot will be filled now.
Producer-Consumer problem is a classical synchronization problem in the operating system. With the presence of more than one process and limited resources in the system the synchronization problem arises. If one resource is shared between more than one process at the same time then it can lead to data inconsistency.
I think the code doesn't make sense this way. The loop never ends, so the line in question can be never reached.
The code didn't originally contain that line, and it was added by an anonymous editor in March 2009. I removed that line now.
In general, code on Wikipedia is often edited by many people over a long period of time, so it's quite easy to introduce bugs into it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With