Semaphore vs Mutex in Producer/Consumer

☆樱花仙子☆ 提交于 2020-03-22 09:22:28

问题


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

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?


回答1:


I believe the reason is that what you'd need is something similar to a condition variable (And not just a mutex (A monitor)), or sleeping in a loop that locks/unlocks. The reason is that you don't just have a shared resource, each of the two threads has a different condition on which they want to use the resource (Buffer is full, buffer is empty). I think for these kind of problems in general, using semaphores is preferred over monitors (Since they can handle more than one resource). However, I do not know why, in particular, semaphores are the preferred solution over monitors for this problem.




回答2:


Because if you only use a lock/mutex, you cannot prevent the consumer from taking the lock/mutex immediately after she frees the lock/mutex. This may, for example, result in a scenario where the buffer is empty but the producer does not take the lock/mutex for a time.




回答3:


for what i understand.

Please read these two scenarios.

First scenario

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.

Second scenario

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.

For producer and consumer,

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

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.



来源:https://stackoverflow.com/questions/52125243/semaphore-vs-mutex-in-producer-consumer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!