具有条件变量的生产者 - 消费者

时间:2016-01-12 05:46:29

标签: c

我正在使用条件变量查看消费者生产者问题的标准解决方案(来自斯坦福大学的网站)

char buffer[SIZE];
int count = 0, head = 0, tail = 0;
struct lock l;
struct condition notEmpty;
struct condition notFull;

lock_init(&l);
condition_init(&notEmpty);
condition_init(&notFull);

void put(char c) {
    lock_acquire(&l);
    while (count == SIZE) {
        condition_wait(&notFull, &l);
    }
    count++;
    buffer[head] = c;
    head++;
    if (head == SIZE) {
        head = 0;
    }
    condition_signal(&notEmpty, &l);
    lock_release(&l);
}

char get() {
    char c;
    lock_acquire(&l);
    while (count == 0) {
        condition_wait(&notEmpty, &l);
    }
    count--;
    c = buffer[tail];
    tail++;
    if (tail == SIZE) {
        tail = 0;
    }
    condition_signal(&notFull, &l);
    lock_release(&l);
    return c;
}

我的问题是为什么我需要两个条件?为什么它不适用于一个?当缓冲区已满时,它将向消费者发出信号,当缓冲区为空时,它将使用相同的信号向生产者发出信号。

0 个答案:

没有答案