Posix 信号量 =>如何在一段时间后关闭信号量。生产者-消费者问题
我正在通过生产者读取文件,并由消费者将它们写入其他文件,当生产者读取输入文件时,我需要关闭其中一个信号量,并且消费者不再等待生产者将一些新输入插入到缓冲区。有什么办法可以做到这一点吗?
问候...
I am reading files by produces and writing them to the other files by consumers and when the input files are read by the producers I need to close one of the semaphore and consumers do not wait any more for producers for inserting some new input to buffer. Is there any way to do that?
Regards...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
几种可能性:
sem_wait()
,在那里它们可以检查EINTR
返回代码。这也需要仔细编码以避免竞争。我对 POSIX 信号处理不是特别熟悉,但我确信它有自己的一套包袱,您需要非常小心才能正确处理。当然,一旦完成,某人(生产者线程?)需要等待所有消费者线程清理 - 可能通过对它们执行
pthread_join()
- 在信号量被销毁/关闭之前。如果您已经使用信号量编码了某些内容,则条件变量选项可能是一个更大的变化,并且在生产和消费(也许)的正常情况下它可能不那么高效。但我敢打赌,推理可能的竞争条件并正确处理它们会更容易。请注意,我并不是说这很容易,只是说它可能会更容易。
A few possibilities:
pthread_kill()
to send a signal to any waiting consumers. This should kick them out of thesem_wait()
, where they can check for theEINTR
return code. This also would need to be coded carefully to avoid races. I'm not particularly familiar with POSIX signal handling, but I'm sure it comes with its own set of baggage that you need to be very careful in handling correctly.Of course, once that's been done someone (the producer thread?) needs to wait for all the consumer threads to clean up - probably by doing a
pthread_join()
on them - before the semaphore is destroyed/closed.The condition variable option is probably a bigger change if you already have something coded up using semaphores, and it might not be as performant in the normal case when are being produced and consumed (maybe). But I'd bet that it's easier to reason about the possible race conditions and handle them correctly. Note that I don't say it's easy, just that it might be easier.