dispatch_group
的作用:
把一组任务提交到队列中,这些队列可以不相关,然后监听这组任务完成
几个常用的方法
*1- dispatch_group_create() 创建一个任务调度组
*2- dispatch_group_async() 将任务异步提交到任务调度组里
*3- dispatch_group_enter/dispatch_group_leave 在不使用dispatch_group_async()提交任务时使用,而且必须配对使用
*4- dispatch_group_notify() 任务执行完毕发出的通知
*5- dispatch_group_wait() 设置任务执行等待时间,在等待时间结束后,如果还没有执行完任务组,则返回。返回 0 代表成功,非 0 代表失败
1.使用dispatch_group_async()
提交任务到任务调度组
- (void)groupUsage1{
/**
* 1 和 (2,3)是并行关系,2 和 3 是串行关系,3 永远在 2 后面
* parallel 并行;serial 串行
*/
dispatch_queue_t parallelQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);//全局队列
dispatch_queue_t serialQueue = dispatch_queue_create("customQueue", 0);//自定义队列
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, parallelQueue, ^{
NSLog(@"Task1");
});
dispatch_group_async(group, serialQueue, ^{
NSLog(@"Task2");
});
dispatch_group_async(group, serialQueue, ^{
NSLog(@"Task3");
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"Task4");
});
}
几种执行情况
1.png 2.png
2.不使用dispatch_group_async()
提交任务到任务调度组
- (void)groupUsage2{
dispatch_queue_t global = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_queue_t custom = dispatch_queue_create("customQueue", 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
dispatch_async(custom, ^{
NSLog(@"Task1");
sleep(1);
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_async(custom, ^{
NSLog(@"Task2");
sleep(2);
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_async(custom, ^{
NSLog(@"Task3");
sleep(3);
dispatch_group_leave(group);
});
NSInteger ret = dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
NSLog(@"WaitResult:%ld",ret);
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"Task4");
});
}
此时为串行队列,执行总耗时 6s
,执行如下
网友评论