引用如果想在dispatch_queue中所有的任务执行完成后在做某种操作,在串行队列中,可以把该操作放到最后一个任务执行完成后继续,但是在并行队列中怎么做呢。这就有dispatch_group 成组操作。
Grouping blocks allows for aggregate synchronization. Your application can submit multiple blocks and track when they all complete, even though they might run on different queues. This behavior can be helpful when progress can’t be made until all of the specified tasks are complete.
打包blocks允许 集合同步操作.程序可以提交多个不同的blocks并且跟踪直到他们执行结束.即使这些被提交到不同的队列上,也可以.
dispatch_group_async
文档注释:Submits a block to a dispatch queue and associates the block with the specified dispatch group.
dispatch_queue_t dispatchQueue = dispatch_queue_create("ted.queue.next", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t dispatchGroup = dispatch_group_create();
dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
NSLog(@"dispatch-1");
});
dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
NSLog(@"dspatch-2");
});
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){
NSLog(@"end");
});
上面的 log1 和log2输出顺序不定,因为是在并发队列上执行,当并发队列全部执行完成后,最后到main队列上执行一个操作,保证“end”是最后输出。 另外,这里也可以不用创建自己的并发队列,用全局的global,那个也是个并发队列. dispatch_get_gloable_queue(0,0);
这里就需要介绍下dispatch_group_notify
文档注释:Schedules a block object to be submitted to a queue when a group of previously submitted block objects have completed.
提交一个预准备的代码块到一个队里,当一组之前提交的block执行完成后,触发.
参考上面的代码就好理解了.
Discussion 具体书名
This function schedules a notification block to be submitted to the specified queue when all blocks associated with the dispatch group have completed. If the group is empty (no block objects are associated with the dispatch group), the notification block object is submitted immediately.
这个方法 实现了一个通知一个指定执行的队列blcok,当这组中所有的blocks执行完成以后,会被通知执行.
当这组的block是空的,那么这个通知的block也会立即触发.
When the notification block is submitted, the group is empty. The group can either be released with dispatch_release or be reused for additional block objects. See dispatch_group_async for more information.
当这个通知的block被提交,这个 组也是空的,那么这个组 既可以手动释放,也可以 被添加的block对象重用.
网友评论