GCD与dispatch_group总结
GCD 可以看作是集合类的操作;
集合是queue,元素是block;
集合只能添加对象,删除对象由系统完成。
同理,NSOperationQueue也可以看作是一个集合管理器。
dispatch_group
A dispatch group is a mechanism for monitoring a set of blocks.
dispatch_group也是一个集合,也是一个机制;
dispatch_group关心的是集合内的任务的整体完成情况。
Note that the blocks in a group may be run on different queues.
The dispatch group keeps track of how many blocks are outstanding, and GCD retains the group until all its associated blocks complete execution.
dispatch_group不关心任务被派发到那个queue,只关心任务的个数;
方式一、
void dispatch_group_async(dispatch_group_t group, dispatch_queue_t queue, dispatch_block_t block);
这种方式可能对传入的block进行了修改,
底层也是使用方式二实现的。
方式二 dispatch_group_leave dispatch_group_enter
这种方式只引起dispatch_group计数的变化,不关心引起变化的原因是queue一个block,还是一个普通的异步实现。
dispatch_group是一个关联任务计数器,只是计数器。
至于任务是什么,不关心。
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group,dispatch_get_global_queue(0, 0), ^{
sleep(3);
NSLog(@"任务0完成");
});
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
sleep(5);
NSLog(@"任务1完成");
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
sleep(8);
NSLog(@"任务2完成");
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_async(dispatch_get_main_queue(), ^{
sleep(1);
NSLog(@"任务3完成");
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_async(dispatch_get_main_queue(), ^{
sleep(1);
NSLog(@"任务4完成");
dispatch_group_leave(group);
});
dispatch_group_enter(group);
[self performSelector:@selector(dsscc:) withObject:group afterDelay:4];
dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
NSLog(@"任务all完成");
});