原文地址: http://blog.csdn.net/qq_31810357/article/details/78906308 未经许可,严禁转载!
GCD使用 dispatch_group_notify
、dispatch_group_enter
、dispatch_group_leave
处理多线程同步操作
一、简介
dispatch_group_enter:通知group,下面的任务马上要放到group中执行。
dispatch_group_leave:通知group,任务完成了,该任务要从group中移除。
通常两者穿插于任务中;
二、测试
- (void)syncActionTest
{
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
//模拟多线程耗时操作
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
sleep(3);
NSLog(@"%@----Block1结束",[NSThread currentThread]);
dispatch_group_leave(group);
});
NSLog(@"%@----1结束",[NSThread currentThread]);
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
sleep(3);
NSLog(@"%@----Block2结束",[NSThread currentThread]);
dispatch_group_leave(group);
});
NSLog(@"%@----2结束",[NSThread currentThread]);
dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"%@---全部结束",[NSThread currentThread]);
});
});
}
三、应用
常见如 : 多图片上传, 在上传完所有图片后将imgUrl数组上传到服务器
dispatch_group_t group = dispatch_group_create();
__weak DespritionViewController *weakSelf = self;
for (UIImage *image in self.arrDataSources) {
dispatch_group_enter(group);
[ZDUserHttpRequest uploadImage:image andType:@"1" completion:^(NSString *picUrl) {
dispatch_group_leave(group);
if (picUrl) {
[weakSelf.picUrlArr addObject:picUrl];
} else {
[SVProgressHUD showErrorWithStatus:@"上传失败,请重试"];
}
} failed:^(NSURLSessionDataTask *task, NSError *error) {
dispatch_group_leave(group);
}];
}
dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
do something...
});
});