Last active
August 29, 2015 14:17
-
-
Save wanewang/affa827b7dd817424c3d to your computer and use it in GitHub Desktop.
An abstract about block with multi async task
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// First | |
dispatch_group_t group = dispatch_group_create(); | |
dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ { | |
// block1 | |
NSLog(@"Block1"); | |
[NSThread sleepForTimeInterval:5.0]; | |
NSLog(@"Block1 End"); | |
}); | |
dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ { | |
// block2 | |
NSLog(@"Block2"); | |
[NSThread sleepForTimeInterval:8.0]; | |
NSLog(@"Block2 End"); | |
}); | |
dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ { | |
// block3 | |
NSLog(@"Block3"); | |
}); | |
dispatch_release(group); | |
// Second | |
// create a group | |
dispatch_group_t group = dispatch_group_create(); | |
// pair a dispatch_group_enter for each dispatch_group_leave | |
dispatch_group_enter(group); // pair 1 enter | |
[self computeInBackground:1 completion:^{ | |
NSLog(@"1 done"); | |
dispatch_group_leave(group); // pair 1 leave | |
}]; | |
// again... (and again...) | |
dispatch_group_enter(group); // pair 2 enter | |
[self computeInBackground:2 completion:^{ | |
NSLog(@"2 done"); | |
dispatch_group_leave(group); // pair 2 leave | |
}]; | |
// Next, setup the code to execute after all the paired enter/leave calls. | |
// | |
// Option 1: Get a notification on a block that will be scheduled on the specified queue: | |
dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ | |
NSLog(@"finally!"); | |
}); | |
// Option 2: Block an wait for the calls to complete in code already running | |
// (as cbartel points out, be careful with running this on the main/UI queue!): | |
// | |
// dispatch_group_wait(group, DISPATCH_TIME_FOREVER); // blocks current thread | |
// NSLog(@"finally!"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment