Objective-C生产者消费者之NSCondition实现

生产者队列
- (void)scheduleProducerQueue {  
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        UIImage *image = ;//produce an image;
        if (image) {
            [self.condition lock];//请求加锁,成功后开始操作products
            [self.products addObject:image];
            [self.condition signal];
            [self.condition unlock];
        }
    }];
    [self.producerQueue addOperation:operation];
}

消费者队列
- (void)scheduleConsumerQueue {
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        [self.condition lock];
        while (self.products.count == 0) {
            [self.condition wait];
        }
        UIImage *image = self.products.firstObject;
        [self.products removeObjectAtIndex:0];
        //do something with image
        [self.condition unlock];
    }];
    [self.consumerQueue addOperation:operation];
}

变量

- (NSCondition *)condition {
    if (!_condition) {
        _condition = [[NSCondition alloc] init];
    }
    return _condition;
}

//使用NSOperationQueue是为了方便cancel
- (NSOperationQueue *)producerQueue {
    if (!_producerQueue) {
        _producerQueue = [[NSOperationQueue alloc] init];
        [_producerQueue setMaxConcurrentOperationCount:2];
    }
    return _producerQueue;
}

- (NSOperationQueue *)consumerQueue {
    if (!_consumerQueue) {
        _consumerQueue = [[NSOperationQueue alloc] init];
        [_consumerQueue setMaxConcurrentOperationCount:2];
    }
    return _consumerQueue;
}

- (NSMutableArray *)products {
    if (!_products) {
        _products = [[NSMutableArray alloc] initWithCapacity:3];
    }
    return _products;
}

你可能感兴趣的:(Objective-C生产者消费者之NSCondition实现)