生产者消费者我应该使用互斥量还是信号量

Producer Consumer should I use a mutex or a semaphore

我有 2 个线程,producer 线程通过互联网套接字接收一些数据,构造一个对象并将其添加到队列中,consumer 线程从同一个队列中弹出项目并执行一些处理。

由于两个线程都修改了队列(分别通过入队和出队),我认为在两个线程中使用互斥锁就足够了。这是一个好方法还是我应该使用信号量?如果是,为什么?

两者都可以工作。这取决于实际设计的细节。您将同时允许多少 producer/consumer 个请求?它真的仅限于两个线程,还是随着更多请求的出现,代码会产生其他线程?

我发现这篇短文 blog 很有趣。它讨论并比较了 MutexSemaphore,可能会给您一些想法。

"A mutex object allows multiple process threads to access a single shared resource but only one at a time. On the other hand, semaphore allows multiple process threads to access the finite instance of the resource until available. In mutex, the lock can be acquired and released by the same process at a time."

C 中的示例