【问题标题】:Why do we need 2 variables for Semaphores in the Producer Consumer problem?为什么在生产者消费者问题中我们需要 2 个信号量变量?
【发布时间】:2018-11-11 02:05:44
【问题描述】:

Producer Consumer 的标准实现方式如下:

  • useQueue互斥体
  • emptyCount 大小的信号量 N
  • fullCount 大小的信号量 N

制作:

down(emptyCount)
down(useQueue)
putItemIntoQueue(item)
up(useQueue)
up(fullCount)

消费:

down(fullCount)
down(useQueue)
item ← getItemFromQueue()
up(useQueue)
up(emptyCount)

如果down 具有非正值,则线程等待。 up 增加计数

取自this维基百科文章

为什么我们不能有类似的东西:

class NewSemaphore {
    int capacity, permits;

    /**
     * Initialize the semaphore with a max capacity
     * @param n the max capacity
     */
    NewSemaphore(int n) {
        capacity = n;
        permits = 0;
    }

    /**
     * We usually never check this. Check if it's within limits.
     * If not, wait
     */
    synchronized void up() {
        if (permits >= capacity) {
            wait();
        } else {
            permits++;
            notify();
        }
    }

    /**
     * Standard down/acquire function
     */
    synchronized void down() {
        if (permits <= 0) {
            wait();
        } else {
            permits--;
            notify();
        }
    }
}

这将被称为:

制作:

up(mySemaphore)
down(useQueue)
putItemIntoQueue(item)
up(useQueue)

消费:

down(mySemaphore)
down(useQueue)
item ← getItemFromQueue()
up(useQueue)

为什么我们需要两个不同的变量emptyCountfullCount

【问题讨论】:

  • Wjat 是否“同步”,因为您似乎在里面等待?
  • 这是Java提供的监视器。用于对信号量对象进行原子语句

标签: operating-system synchronization mutex semaphore producer-consumer


【解决方案1】:

不,两个信号量不是必需的,这里是用 C 编写的单个信号量解决方案,请在此处查看: https://github.com/heguihua/unisem

【讨论】:

    【解决方案2】:

    有两个信号量,因为我们要检查两件事。一是消费者在没有东西消费时等待,二是生产者在队列满时等待。

    您的想法是让生产者继续生产,直到内存或其他资源用完为止。

    【讨论】:

    • 信号量有一个上限。它不会继续生产。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 2016-08-01
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多