what is the best way to wait until an object is removed from array

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);

}

});

}

Can anyone let the best practice to wait until an object is removed from array?

There isn’t a way to answer this without more context. The straw man code you posted has serious problems:
  • It mutates the array from multiple threads concurrently, which is not supported and likely to crash.

  • It schedules a block on a concurrent queue, something that’s generally frowned up, and then blocks it waiting for a semaphore, which is a very bad idea.

The last point is the key one. What is the relationship between the code putting items into this array and the code pulling them out? If you can have an unbounded number of threads putting items into the array, that means you can have an unbounded number of threads blocked waiting for space, and that’s not going to end well.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"

WWDC runs Mon, 22 Jun through to Fri, 26 Jun. During that time all of DTS will be busy with conference duties.
what is the best way to wait until an object is removed from array
 
 
Q