【发布时间】:2023-03-17 19:32:01
【问题描述】:
我正在尝试使用 cond 变量和信号量来比较生产者消费者问题的实现。
使用 cond 变量实现:
acquire(m); // Acquire this monitor's lock.
while (!p) { // While the condition/predicate/assertion that we are waiting for is not true...
wait(m, cv); // Wait on this monitor's lock and condition variable.
}
// ... Critical section of code goes here ...
signal(cv2); -- OR -- notifyAll(cv2); // cv2 might be the same as cv or different.
release(m);
使用信号量实现:
produce:
P(emptyCount)
P(useQueue)
putItemIntoQueue(item)
V(useQueue)
V(fullCount)
为什么信号量实现不像 cond 变量实现那样使用 while 循环来检查条件?
while (!p) { // While the condition/predicate/assertion that we are waiting for is not true...
wait(m, cv); // Wait on this monitor's lock and condition variable.
}
Why do you need a while loop while waiting for a condition variable
【问题讨论】:
标签: conditional-statements mutex semaphore