Unix信号量问题
有没有办法用unix信号量设置它们的值?我需要始终从多个消费者调用 post() ,并且偶尔调用 wait() ,它将等待下一个 post() 发生。
如何才能实现这一目标?
原因是我正在实现生产者/消费者问题(1 个生产者/最多 2 个消费者)。每个消费者都有一个内部队列,其中存储似乎无法放在输出上的项目,因为其他消费者仍然缺少其他数据包,因此它们都以正确的顺序输出(因为它们来自生产者) 。当任何队列被认为已满时(比方说,有 10 个项目),我希望该进程等待,直到另一个进程完成其工作(因为只有 2 个进程,我保证其他进程的数据包正在产生的是我需要开始做一些输出的数据包!)。
我的想法是,每次消费者处理任何内容并查找将其放入输出中时,它都应该调用信号量上的 post() 之类的东西。每次消费者的队列已满时,它都应该对同一个信号量执行某种 wait() 操作。这样,当另一个消费者完成其工作时,这个消费者就会被唤醒。
遇到这种情况应该如何解决呢?我走在正确的道路上吗?在这个项目中,我仅限于使用信号量和共享内存。
当然,我们的想法是尽可能避免旋转。
谢谢
Is there a way for, with unix semaphores, set their values? I'm in need of always calling post() from multiple consumers and once in a while call a wait() that'll wait until the next post() happens.
How can this be achieved?
The reason for this is that I am implementing the Producer / Consumer problem (1 producer / up to 2 consumers). Each consumer has an internal queue where it stores items that it seems can't be put on the output yet as there are still other packets missing from others consumers so that they are all output in the correct order(as they came from the producer). When any of the queues is considered full (let's say, with 10 items), I'd want that process to wait until the other process finishes its work (as there are only 2 processes, I have the guarantee that the packet that other process is yielding is the packet I need to start doing some output!).
My idea is that each time a consumer processes anything and looks up to put it in the output, it should make a call on something like post() on a semaphore. Every time a consumer has its queue full, it should do a kind of wait() on that same semaphore. This way, when the other consumer finishes its work, this one is waked up.
How should solve this situation? Am I on the right path? I am limited to using semaphores and shared memory, in this project.
Of course, the idea is to avoid as much as possible spinning.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看来您最需要一个障碍来同步您的消费者。
Posix 似乎给出了它的实现(pthread_barrier_*)。
因此,请与消费者数量建立共同的障碍;当消费者完成时,它必须“在屏障处等待”。
否则,您可以使用另一个信号量来实现它。
It seems that you mostly need a barrier to synchronize your consumers.
It seems that Posix gives an implementation of it (pthread_barrier_*).
So create your shared barrier with the number of consumers; when a consumer finishes, it must "wait at the barrier".
Otherwise, you can implement it with another semaphore.