生产者消费者我应该使用静音或信号量

发布于 2025-01-26 14:31:10 字数 211 浏览 1 评论 0 原文

我有2个线程, producer 线程通过Internet插座接收一些数据,构造对象并将其添加到队列中, consumer thread thread thread从同一队列和进行一些处理。

由于这两个线程分别通过重点和脱水来修改队列,因此我认为在两个线程中使用互斥X应该足够。这是一种很好的方法,还是我应该使用信号量?如果是这样,为什么?

I have 2 threads, the producer thread receives some data over an internet socket, constructs an object and adds it to a queue and the consumer thread pops items from that same queue and does some processing.

Since both threads modify the queue (by enqueuing and dequeuing respectively) I think using a mutex in both threads should be sufficient. Is this a good approach or should I use a semaphore? If so, why?

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

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

发布评论

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

评论(1

初吻给了烟 2025-02-02 14:31:10

可以做任何一个工作。这取决于实际设计的细节。您将同时允许多少个生产者/消费者请求?它真的限于两个线程,还是代码会随着更多请求而产生其他线程?

我发现此简短 blog 有趣。它讨论并比较了 mutex 信号量,并可能给您一些想法。

“ a mutex 对象允许多个进程线程访问单个共享资源,但一次只能访问一个。另一方面,信号量
允许多个进程线程访问
资源直至可用。在Mutex中,可以获取锁,并且
一次由同一过程发布。”

Either can be made to work. It depends on details of the actual design. How many producer/consumer requests will you allow simultaneously? Is it truly limited to two threads, or will the code spawn others as more requests occur?

I found this short blog interesting. It discusses and compares both the Mutex and Semaphore and may give you some ideas.

"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."

Examples in C

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