Pergunta

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.

Foi útil?

Solução 2

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.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top