Note that there are some explanatory texts on larger screens.

plurals
  1. POMultithreading: classical Producer Consumer algorithm
    primarykey
    data
    text
    <p>Something I don't get about the classical algorithm for the Producer-Consumer problem (from Wikipedia:)</p> <pre>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) } } </pre> <p>I note that both producers and consumers lock 'mutex' prior to messing with the buffer, and unlock it thereafter. If that is the case, i.e. only a single thread is accessing the buffer at any given moment, I don't really see how the above algo differs from a simple solution that entails only putting a guarding mutex over the buffer:</p> <pre> semaphore mutex = 1 procedure producer() { while (true) { item = produceItem() flag = true while (flag) { down(mutex) if (bufferNotFull()) { putItemIntoBuffer(item) flag = false } up(mutex) } } } procedure consumer() { while (true) { flag = true while (flag) { down(mutex) if (bufferNotEmpty()) { item = removeItemFromBuffer() flag = false } up(mutex) } consumeItem(item) } } </pre> <p>Only thing I can think of that necessitates using the 'fillCount' and 'emptyCount' semaphores is <em>scheduling</em>.</p> <p>Maybe the first algo is for making sure that in a state where 5 consumers are waiting on an empty buffer (zero 'fillCount'), it is assured that when a new producer comes along, it will go past its "down(emptyCount)" statement quickly and get the 'mutex' quickly.</p> <p>(whereas in the other solution the consumers will needlessly get the 'mutex' only to relinquish it until the new producer gets it and inserts an item).</p> <p>Am I right? Am I missing something?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload