Everyone Asleep

A one-slot bounded buffer with one producer and two consumers, sharing a single condition variable. Both waits are while loops, so a woken thread always rechecks before proceeding:

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

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

The assertion inside get() never fires now, but the program still hangs, with all three threads asleep in Cond_wait. Which event puts it there?

A

Both consumers waited on the same condition variable at once, and a condition variable holds only one waiter.

B

A consumer that had just emptied the buffer signaled the shared condition variable and woke the other consumer instead of the producer. The woken consumer rechecked, found the buffer empty, and slept again, leaving nobody to wake the producer.

C

The producer's signal was lost because it arrived while no thread was waiting on the condition variable.

D

The while loop rechecked the condition and put the consumer straight back to sleep before the producer could reacquire the mutex.