Skip to content

Instantly share code, notes, and snippets.

@kastiglione
Forked from alloy/gist:5679340
Last active December 17, 2015 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kastiglione/5679834 to your computer and use it in GitHub Desktop.
Save kastiglione/5679834 to your computer and use it in GitHub Desktop.
- (NSArray *)mapConcurrent;
{
NSArray *originals = self.listOfObjects;
NSUInteger count = originals.count;
NSMutableArray *collected = [[NSMutableArray alloc] initWithCapacity:count];
for (NSUInteger i = 0; i < count; i++) {
[collected addObject:[NSNull null]];
}
dispatch_semaphore_t itemLock = dispatch_semaphore_create(1);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply(count, queue, ^(size_t i) {
id original = originals[i];
id result = [original performWork];
dispatch_semaphore_wait(itemLock, DISPATCH_TIME_FOREVER);
collected[i] = result;
dispatch_semaphore_signal(itemLock);
});
dispatch_release(itemLock);
return collected;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment