dispatch_group、dispatch_group_enter、dispatch_group_leave
只有一层异步任务,多个任务并发执行,完成后通知:
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (int i = 0; i<10; i++) {
NSLog(@"任务1 ============== 第%d个任务",i);
}
});
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (int i = 0; i<10; i++) {
NSLog(@"任务2 ============== 第%d个任务",i);
}
});
dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"完成");
});
输出结果:任务1、2执行不确定,但一定是两个都完成之后才会通知
注:如果任务里面又包含异步任务,这个通知会执行时间不定可能是任务1自行一次就通知,也可能2执行一次就通知,要想实现上面的效果,在任务1、2完成之后通知就需要用到
dispatch_group_enter和dispatch_group_leave
示例代码:
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
for (int i = 0; i<10; i++) {
NSLog(@"任务1 ============== 第%d个任务",i);
}
dispatch_group_leave(group);
});
});
dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (int i = 0; i<10; i++) {
NSLog(@"任务2 ============== 第%d个任务",i);
}
dispatch_group_leave(group);
});
});
dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"完成");
});