本文介绍了同步生产者,使用者和生产者队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个生产者和一个消费者。生产者用对象填充其内部队列,消费者逐一地取得这些对象。我想要使​​cosumer与生产者同步,这样当没有对象准备就绪时,消费者阻塞,并且我想使生产者与自身同步,以便在队列满时停止产生(并且当有空间时再次启动) 。我怎么做?我可以使用 / 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];
}
}

@end

bufferFreeSlots 初始化为最大队列大小。到目前为止,它似乎工作,但上帝知道这是一种信仰的行为,而不是一个坚定的信心。


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];
    }
}

@end

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.

这篇关于同步生产者,使用者和生产者队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 17:46