多进程同步——比信号量更好的选择?
我有一个在多个生产者和多个消费者之间共享的队列资源。都是独立的进程;没有一个进程“拥有”该队列。
根据实现的本质,必须控制对队列的访问,并且在任何给定时刻都必须只允许一个进程压入或弹出。
我认为使用 POSIX 命名的信号量将是正确的解决方案,但是一些细节让我困扰。 (顺便说一句,这是一个仅限 Linux 的实现。)
我什么时候(如果有的话)应该执行 sem_unlink?有什么理由实际删除队列吗?
我担心在锁定队列信号量时进程会终止。有什么好的办法解决这个问题吗?我可以在尝试获取锁定时进行定时等待,但如果超时到期,我现在就会遇到竞争条件。
对于像这样的简单的二进制锁有更好的解决方案吗?也许使用 fcntl 和/或独占打开的锁文件?
I've got a queue resource that is shared across multiple producers and multiple consumers. All are independent processes; no one process "owns" the queue.
By nature of the implementation access to the queue must be controlled and only one process must be allowed to push or pop at any given moment.
I figured using a POSIX named semaphore would be the right solution, however a few of the details are bothering me. (This is a Linux-only implementation, btw.)
When (if ever) should I do a sem_unlink? Is there any reason to actually remove the queue?
I'm concerned about a process dying while holding the queue semaphore locked. Is there any good way around this? I can do a timed wait when trying to get the lock, but if the timeout expires I've now got a race condition.
Is there a better solution for a simple binary lock like this? Perhaps a lockfile using fcntl and/or exclusive opens?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
文件锁的优点是在进程意外死亡时可以解锁。我认为它们最适合您的场景。
我可以想象当我需要它们支持的更复杂的语义时使用信号量(它们不仅仅支持您想到的互斥体用法),但如果我确实使用它们,我需要某种方法在过早死亡的情况下执行内务处理。我观察到 Windows 上的 Lotus Notes 有一个“ZapNotes”管家,可以在我认为类似的“不应该发生”的情况下进行整理。
File locks have the benefit of unlocking in the event of of unexpected process death. I think that they best suit your scenario.
I can imagine using semaphores when I need the more complex semantics they support (they do more than support the mutex usage you have in mind) but if I do use them I need some way to perform housekeeping in the event of untimely death. I observe that Lotus Notes on Windows has a "ZapNotes" houskeeper that tidies in what I assume are similar "shouldn't happen" scenarios.