Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Producer-consumer with sempahores

Tags:

algorithm

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?

like image 812
Ohad Avatar asked Jan 24 '12 20:01

Ohad


People also ask

What is producer and consumer in semaphore?

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.

How many semaphores are in a producer-consumer?

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.

How does semaphore provide the solution to the Producer-Consumer problem?

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.

What is Producer-Consumer problem with example?

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.


1 Answers

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.

like image 85
svick Avatar answered Oct 15 '22 23:10

svick