Synchronizing producer, consumer and a producer queue
-
29-09-2019 - |
Question
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.
Solution 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.
OTHER TIPS
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.