生產者隊列
- (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;
}
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。