同步生产者、消费者和生产者队列
我有一个生产者和一个消费者。生产者将对象填充到其内部队列,消费者将这些对象一一取出。我想将消费者与生产者同步,以便消费者在没有准备好对象时阻塞,并且我想将生产者与其自身同步,以便当队列已满时它停止生产(并在有空间时重新开始) 。我该怎么做?我能够使用 NSConditionalLock 在没有队列的情况下解决更简单的情况,但使用队列时问题看起来更复杂。
I have a producer and a consumer. Producer fills its internal queue with objects, consumer takes these objects one by one. I want to synchronize the cosumer with the producer, so that the consumer blocks when there are no objects ready, and I want to synchronize the producer with itself, so that it stops producing when the queue is full (and starts again when there’s space). How do I do that? I was able to solve a simpler case without the queue using NSConditionalLock
, but with the queue the problem looks more complex.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以考虑使用一对 NSOperationQueues 或调度队列。如果需要,让生产操作(在生产者队列中)在主线程上将消息发送到将消费操作添加到消费者队列的对象。
You might consider using a pair of NSOperationQueues or dispatch queues. Have your production operations (in the producer queue) send messages, on the main thread if necessary, to an object that adds consumption operations to the consumer queue.
我最终使用了两个信号量,
objectsReady
和bufferFreeSlots
:bufferFreeSlots
被初始化为最大队列大小。到目前为止,这似乎有效,但上帝知道这是一种信心的行为,而不是坚定的信心。I ended up using two semaphores,
objectsReady
andbufferFreeSlots
:The
bufferFreeSlots
is initialized to the maximum queue size. So far it seems to work, but God knows this is an act of faith, not a solid confidence.