0

I am trying to compare produer consumer problem implementation using cond variable and semaphores.

Implementation using cond variable:

acquire(m); // Acquire this monitor's lock.
while (!p) { // While the condition/predicate/assertion that we are waiting for is not true...
    wait(m, cv); // Wait on this monitor's lock and condition variable.
}
// ... Critical section of code goes here ...
signal(cv2); -- OR -- notifyAll(cv2); // cv2 might be the same as cv or different.
release(m); 

Implementation using semaphore:

produce:
    P(emptyCount)
    P(useQueue)
    putItemIntoQueue(item)
    V(useQueue)
    V(fullCount)

why semaphore implementation is not using while loop to check the condition like in cond variable implementation.?

while (!p) { // While the condition/predicate/assertion that we are waiting for is not true...
        wait(m, cv); // Wait on this monitor's lock and condition variable.
    }

Why do you need a while loop while waiting for a condition variable

Community
  • 1
  • 1
user1762571
  • 1,888
  • 7
  • 28
  • 47

1 Answers1

0

Grabbing a semaphore does use a tight loop internally, just like the cond version, but it yields execution back to the scheduler in each iteration to not waste resources like a busy loop would.

When the scheduler has executed some other process for a while, it yields execution back to your thread. If the semaphore is available now, it is grabbed; otherwise it yields back to the scheduler to let some other process run some more before retrying.

Filip Haglund
  • 13,919
  • 13
  • 64
  • 113