生产者/消费者中的信号量与互斥量 [英] Semaphore vs Mutex in Producer/Consumer

查看:633
本文介绍了生产者/消费者中的信号量与互斥量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在生产者-消费者问题中,为什么我们经常建议使用信号量而不是使用锁/互斥锁?

In the Producer-Consumer problem, why are we often suggested use to semaphores instead of using a lock/mutex?

我看不到使用信号量的正当理由,因为我们只有 2个线程进行协调.在这种情况下,锁似乎更容易编写代码并进行推理,因为一个线程将锁定缓冲区然后释放它,以便另一个线程可以执行相同的操作.只有2个线程,所以我看不到信令的使用.

I don't see a valid reason to use a semaphore because we only have 2 threads coordinating. In this case a lock seems much easier to code and reason about because a thread will lock the buffer then free it so the other thread can do the same. There are only 2 threads so I don't see the use of signaling.

有人可以说为什么建议通常将信号量用于生产者-消费者吗?

Can anyone say why it is suggested to use semaphores usually for producer-consumer?

推荐答案

据我所知.

请阅读以下两种情况.

第一种情况

信号量就像摩托车的钥匙.假设您的摩托车最多有两个座位.让我们以摩托车为资源,座位为共享内存中的两个缓冲空间.

Semaphore is like a key for your motorbike. Lets say your motorbike has a maximum of two seats. Lets think that the motorbike is the resource and the seats are the two buffer space inside the shared memory.

第二种情况

让我们想到一个男孩腹泻.他赶到洗手间,但发现他的兄弟仍在使用洗手间.他需要等到他的兄弟完成之后:)让我们以为洗手间是一个很大的回忆.

Let's think of a boy having diarrhea. He rushed to the bathroom but found out that his brother is still using the bathroom. He need to wait until his brother is done :) Lets think that the bathroom is a one big memory.

对于生产者和消费者,

让我们说生产者的商店每天有最多x件商品.

Lets say the producer has a store with x maximum items for each day.

消费者根据商品的可用性购买x件商品.

The consumer buys x items depending on the availability of the item.

这意味着互斥量和信号量具有自己的目的或应用程序,具体取决于您的需求. 仅仅是生产者-消费者的想法,信号量就赢了.

This means that mutex and semaphore have their own purpose or application depending on what you need. It is just that for Producer-consumer idea, the semaphore has won.

这篇关于生产者/消费者中的信号量与互斥量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆