我正在使用条件变量查看消费者生产者问题的标准解决方案(来自斯坦福大学的网站)
char buffer[SIZE];
int count = 0, head = 0, tail = 0;
struct lock l;
struct condition notEmpty;
struct condition notFull;
lock_init(&l);
condition_init(¬Empty);
condition_init(¬Full);
void put(char c) {
lock_acquire(&l);
while (count == SIZE) {
condition_wait(¬Full, &l);
}
count++;
buffer[head] = c;
head++;
if (head == SIZE) {
head = 0;
}
condition_signal(¬Empty, &l);
lock_release(&l);
}
char get() {
char c;
lock_acquire(&l);
while (count == 0) {
condition_wait(¬Empty, &l);
}
count--;
c = buffer[tail];
tail++;
if (tail == SIZE) {
tail = 0;
}
condition_signal(¬Full, &l);
lock_release(&l);
return c;
}
我的问题是为什么我需要两个条件?为什么它不适用于一个?当缓冲区已满时,它将向消费者发出信号,当缓冲区为空时,它将使用相同的信号向生产者发出信号。