具有有限缓冲区的生产者/消费者,具有信号量的多个生产者/消费者

发布于 2024-12-28 02:56:22 字数 663 浏览 4 评论 0原文

我有点陷入多重消费者/生产者问题。它出现在我的讲义中,但我根本无法理解为什么单一消费者/生产者方法行不通。

1 个消费者和 1 个生产者的典型方法如下所示:

Producer : 
    while(true)
        emptyBuffers.P();
        mutex.P();
        buffer.insert(produced item);
        mutex.V();
        fullBuffers.V();

Consumer : 
    while(true)
        fullBuffers.P();
        mutex.P();
        buffer.consume(consumed item);
        mutex.V();
        emptyBuffers.V();

如果我有超过 1 个生产者和/或超过 1 个消费者,为什么这不起作用?我到处都找过,但找不到我理解的答案:s。

互斥信号量确保没有 2 个进程同时在缓冲区中工作,因此我不知道如果您有更多进程,此属性可能会如何更改...

“解决方案”是将互斥锁更改为ProducerMutex 和 ConsumerMutex。但现在这意味着生产者和消费者可以同时在缓冲区中,这是不允许的,对吧?

我真的不明白:s

I'm a bit stuck on the multiple consumer/producer problem. It appears in my lecture notes, but I simply cannot understand why the single consumer/producer approach won't work.

The typical approach for 1 consumer and 1 producer looks like this :

Producer : 
    while(true)
        emptyBuffers.P();
        mutex.P();
        buffer.insert(produced item);
        mutex.V();
        fullBuffers.V();

Consumer : 
    while(true)
        fullBuffers.P();
        mutex.P();
        buffer.consume(consumed item);
        mutex.V();
        emptyBuffers.V();

Why will this not work if I have more than 1 producer and/or more than 1 consumer? I've looked everywhere, but I can't find an answer I understand :s.

The mutex semaphore makes sure there are no 2 processes working in the buffer at the same time, so I don't see how this property can possibly change if you have more processes...

The 'solution' is that you change the mutex into a ProducerMutex and a ConsumerMutex. But now that would mean a producer and a consumer CAN be in the buffer at the same time, which should not be allowed, right?

I'm really not getting this :s

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡莣 2025-01-04 02:56:22

这是 http://en.wikipedia.org/wiki/Producer-consumer_problem(模命名)。当然,这也表明您不需要 1P/1C 版本的互斥体(如果缓冲区只有 1 个插槽,则这将是有效的)。但它也与 http://cs.gmu 中给出的解决方案相同。 edu/cne/modules/ipc/purple/prodsem.html

底线:我认为你已经得到了这个很好,而无论是谁给你这个 2-mutex“解决方案”都不是。

That's the solution given in http://en.wikipedia.org/wiki/Producer-consumer_problem (modulo naming). Of course, that also states that you don't need the mutex for the 1P/1C version (which would be valid if the buffer had only 1 slot). But its also the same solution as given in http://cs.gmu.edu/cne/modules/ipc/purple/prodsem.html.

Bottom line: I think you're getting this just fine, and whomever gave you this 2-mutex "solution" isn't.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文