Synchronizing producer, consumer and a producer queue

时光怂恿深爱的人放手 提交于 2019-12-13 05:07:59

问题


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.


回答1:


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.




回答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.



来源:https://stackoverflow.com/questions/3896617/synchronizing-producer-consumer-and-a-producer-queue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!