0

I read the wikipedia about the Producer–consumer problem https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem

It mentioned that in below code it works fine when there is only one producer and consumer. My question is that if producer is doing up(fillCount); and consumer is doing down(fillCount); then the result still correct? because in my opinion it isn't atomic write operation.

semaphore fillCount = 0; // items produced
semaphore emptyCount = BUFFER_SIZE; // remaining space

procedure producer() 
{
    while (true) 
    {
        item = produceItem();
        down(emptyCount);
        putItemIntoBuffer(item);
        up(fillCount);
    }
}

procedure consumer() 
{
    while (true) 
    {
        down(fillCount);
        item = removeItemFromBuffer();
        up(emptyCount);
        consumeItem(item);
    }
}
Howard
  • 143
  • 1
  • 1
  • 12
  • 1
    Try to find an execution where the consumer accesses the newest item while it is still in the process of being written (thus making the lack of atomicity in the write (and, by the way, also the read) relevant). Hint: There isn't one if the semaphores are properly initialized. – EOF May 16 '19 at 15:29
  • 1
    Semaphore have atomic increment and decrement operations, so calling `up` and `down` from different threads will yield the appropriate result. "A semaphore is somewhat like an integer variable, but is special in that its operations(increment and decrement) are guaranteed to be atomic" - https://see.stanford.edu/materials/icsppcs107/23-Concurrency-Examples.pdf – Joel May 16 '19 at 15:54
  • ok, I got it. But if there are many producers and consumers. Isn't the result also correct ? because it's atomic operation. But wiki mentions many threads would be wrong in some cases. https://imgur.com/QlsaaZE – Howard May 16 '19 at 16:17
  • @Howard Example: two writers, w1 and w2 are executing concurrently: `w1` takes index 1 of the buffer, `w2` takes index 2 (btw, how does a writer know which index it should write to?). Say `w2` writes its element faster than `w1`, so it reaches the `up(fillCount)` when `w1`s write is still incomplete. An eager reader was *just* waiting for the semaphore. What does it see? – EOF May 16 '19 at 19:55
  • @EOF 1.One of the producers determines the next empty slot in the buffer 2.Second producer determines the next empty slot and gets the same result as the first producer, so the action two producer do `item = removeItemFromBuffer();` like buffer[fillCount]=item and they choose the same slot would cause error right :) ? – Howard May 17 '19 at 00:26

0 Answers0