前言
你肯定遇到过一个任务必须依赖前面几个异步任务完成之后的数据才能进行的问题,第一想到的解决方案是不是dispatch_group呢,我相信很多人会采用此方案,快告诉我我的猜测没错😄。
dispatch_group简单使用
案例1:
dispatch_queue_t queue = dispatch_queue_create("testqueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
for (int i = 0; i < 5; i ++) {
NSLog(@"任务%d",i);
}
});
dispatch_group_async(group, queue, ^{
NSLog(@"任务5");
});
dispatch_group_notify(group, queue, ^{
NSLog(@"全部任务执行完毕");
});
打印结果:
看到这个结果大家觉得很对有木有,那我们车门焊死往下开~
案例2
dispatch_group_async内部加入async异步操作。
dispatch_queue_t queue = dispatch_queue_create("testqueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
dispatch_async(queue, ^{
for (int i = 0; i < 5; i ++) {
NSLog(@"任务%d",i);
}
});
});
dispatch_group_async(group, queue, ^{
dispatch_async(queue, ^{
NSLog(@"任务5");
});
});
dispatch_group_notify(group, queue, ^{
NSLog(@"全部任务执行完毕");
});
打印结果:
我擦泪,dispatch_group_notify不是最后执行了,那还怎么保证我的最后结果。是不是有点出乎意料,dispatch_group_notify保证的先后顺序在心里是不是有点崩塌。。。,不急车往下开。
案例3
dispatch_queue_t queue = dispatch_queue_create("testqueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
dispatch_async(queue, ^{
for (int i = 0; i < 5; i ++) {
NSLog(@"任务%d",i);
}
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_async(queue, ^{
NSLog(@"任务5");
dispatch_group_leave(group);
});
dispatch_group_notify(group, queue, ^{
NSLog(@"全部任务执行完毕");
});
打印结果:
dispatch_group_enter和dispatch_group_leave
的使用保证了上面情况的结果正确性。再往下看。。。
案例4
dispatch_queue_t queue = dispatch_queue_create("testqueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
dispatch_async(queue, ^{
for (int i = 0; i < 5; i ++) {
NSLog(@"任务%d",i);
}
});
dispatch_group_enter(group);
dispatch_async(queue, ^{
NSLog(@"任务5");
});
dispatch_group_notify(group, queue, ^{
NSLog(@"全部任务执行完毕");
});
打印结果:
只采用了dispatch_group_enter,任务一直没有结束。。。
案例5
dispatch_queue_t queue = dispatch_queue_create("testqueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
dispatch_async(queue, ^{
for (int i = 0; i < 5; i ++) {
NSLog(@"任务%d",i);
dispatch_group_leave(group);
}
});
dispatch_group_enter(group);
dispatch_async(queue, ^{
NSLog(@"任务5");
dispatch_group_leave(group);
});
dispatch_group_notify(group, queue, ^{
NSLog(@"全部任务执行完毕");
});
打印结果:
程序并没有运行结束,已经crash。。
如果dispatch_group_leave比dispatch_group_enter数量多,不好意思老子不干了直接crash。
最后
dispatch_group一般用着没什么问题,出现了上面的情况可以采用dispatch_group_leave比dispatch_group_enter成对出现,必须成对,否则后果自负