I have declared an mutablearray and the count should not exceed 100. If some one calls addObject method to add an item to that array when the count is 100 then that method call should not be executed until someone removes an item so that count will go down below 100. Can we use semaphore or group dispatch for signalling or mutex/NSLock is recommended.
- (void)viewDidLoad {
[super viewDidLoad];
self.array = [[NSMutableArray alloc] initWithCapacity:100];
semaphore = dispatch_semaphore_create(0);
[self addObject:@1];
[self addObject:@2];
[self addObject:@3];
[self addObject:@4];
.
.
.
[self addObject:@100];
[self addObject:@101];
[self removeObjectAtIndex:1];
}
- (void)addObject:(id)object{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self.array addObject:object];
if([self.array count] == 100){
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}
});
}
- (void)removeObjectAtIndex:(NSInteger)index{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self.array removeObjectAtIndex:index];
if([self.array count]<100){
dispatch_semaphore_signal(semaphore);
}
});
}