Everyone Ends Up Asleep

A bounded buffer holds one item. This version already uses while instead of if, so no thread acts on a stale condition:

cond_t cond;  mutex_t mutex;  int count = 0;

void *producer(void *arg) {
    for (int i = 0; i < loops; i++) {
        Mutex_lock(&mutex);
        while (count == 1) Cond_wait(&cond, &mutex);
        put(i);
        Cond_signal(&cond);
        Mutex_unlock(&mutex);
    }
}

void *consumer(void *arg) {
    for (int i = 0; i < loops; i++) {
        Mutex_lock(&mutex);
        while (count == 0) Cond_wait(&cond, &mutex);
        int tmp = get();
        Cond_signal(&cond);
        Mutex_unlock(&mutex);
    }
}

Run it with one producer and two consumers. What still goes wrong?

A

The producer deadlocks on mutex, because Cond_wait does not release the mutex while a second consumer holds it.

B

A consumer's Cond_signal can wake the other consumer instead of the producer. That consumer re-checks, finds the buffer empty, and sleeps again, leaving all three threads asleep.

C

Nothing goes wrong. Changing if to while is the complete fix, and additional consumers only change throughput.

D

A consumer can return from Cond_wait and call get() on a buffer another consumer already drained, tripping the assertion inside get.