Skip to content

Instantly share code, notes, and snippets.

@kylemcdonald
Last active August 29, 2015 14:07
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylemcdonald/73a37371efaf95f22591 to your computer and use it in GitHub Desktop.
Save kylemcdonald/73a37371efaf95f22591 to your computer and use it in GitHub Desktop.
Grand central dispatch examples courtesy of @HalfdanJ
// group of for loops with waiting
int m, n;
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0), ^{
// before all parallel m
dispatch_apply(m, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^(size_t i) {
// parallel m code with i for index
});
// after all parallel m
});
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0), ^{
// before all parallel n
dispatch_apply(n, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^(size_t i) {
// parallel n code with i for index
});
// after all parallel n
});
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
// big calculation async
int k;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0), ^{
// initial async calculations
dispatch_async(dispatch_get_main_queue(), ^{
// jump to main thread
});
// jump back to asynchronous thread
});
// single for loop
int q = 100;
dispatch_apply(q, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^(size_t i) {
// parallel q loop with i for index
// no guarantees about what this prints
cout << i;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment