我有一个生产者和一个消费者。生产者用对象填充其内部队列,消费者逐一地取得这些对象。我想要使cosumer与生产者同步,这样当没有对象准备就绪时,消费者阻塞,并且我想使生产者与自身同步,以便在队列满时停止产生(并且当有空间时再次启动) 。我怎么做?我可以使用 NSConditionalLock 解决一个更简单的情况,但是队列中的问题看起来更复杂。
objectsReady 和 bufferFreeSlots : / p> @implementation生产者 - (id)getNextObject { [objectsReady wait]; id anObject = [[buffer objectAtIndex:0] retain]; [buffer removeObjectAtIndex:0]; [bufferFreeSlots signal]; return [anObject autorelease]; } - (void)decodeLoop { while(1){ [bufferFreeSlots wait]; [buffer push:[self produceAnObject]]; [objectsReady signal]; } } @endbufferFreeSlots 初始化为最大队列大小。到目前为止,它似乎工作,但上帝知道这是一种信仰的行为,而不是一个坚定的信心。
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.
解决方案I ended up using two semaphores, objectsReady and bufferFreeSlots:
@implementation Producer - (id) getNextObject { [objectsReady wait]; id anObject = [[buffer objectAtIndex:0] retain]; [buffer removeObjectAtIndex:0]; [bufferFreeSlots signal]; return [anObject autorelease]; } - (void) decodeLoop { while (1) { [bufferFreeSlots wait]; [buffer push:[self produceAnObject]]; [objectsReady signal]; } } @endThe 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.
更多推荐
同步生产者,使用者和生产者队列
发布评论