【问题标题】:why while loop is not needed in sem_wait?为什么 sem_wait 中不需要 while 循环?
【发布时间】: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


    【解决方案1】:

    抓取信号量确实在内部使用紧密循环,就像cond 版本一样,但它在每次迭代中将执行返回给调度程序,以免像繁忙的循环那样浪费资源。

    当调度程序执行了一段时间的其他进程时,它会将执行返回给您的线程。如果信号量现在可用,则将其抓取;否则它会返回给调度程序,让其他进程在重试之前再运行一些。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-21
      • 2019-10-02
      • 1970-01-01
      • 2022-12-12
      • 1970-01-01
      • 2012-11-07
      相关资源
      最近更新 更多