【发布时间】:2021-08-04 01:00:07
【问题描述】:
我正在查看代码https://www.cse.iitd.ernet.in/~sbansal/os/lec/l25.html 而且我无法理解 Consumer 和 producer 中的等待和通知顺序。 not_full 和 not_empty 条件变量的顺序是否正确?在生产者中,它应该等待 not_full 并通知 not_empty,而在消费者中,它应该等待 not_empty 并通知 notfull。我的理解正确吗?
int head = 0, tail = 0;
struct cv not_full, not_empty;
struct lock qlock;
void produce(char data) {
acquire(&qlock);
(while ((head + 1) % MAX == tail)) {
wait(¬_full, &qlock);
}
queue[head] = data;
head = (head + 1) % MAX;
notify(¬_full); // Here it will notify the consumer to wake up and processes the data
release(&qlock);
}
char consume(void) {
acquire(&qlock);
while () {
wait(¬_empty, &qlock); // consumer will wake up on event from Producer
}
e = queue[tail];
tail = (tail + 1) % MAX;
notify(¬_empty);
release(&qlock);
return e;
}
【问题讨论】:
-
(while ((head + 1) % MAX == tail))和while ()看起来不像 C++
标签: c++ concurrency