另外,GCD还有一些高级用法,例如让后台2个线程并行执行,然后等2个线程都结束后,再汇总执行结果。这个可以用dispatch_group, dispatch_group_async 和 dispatch_group_notify来实现,示例如下:
- dispatch_group_t group = dispatch_group_create();
- dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{
- // 并行执行的线程一
- });
- dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{
- // 并行执行的线程二
- });
- dispatch_group_notify(group, dispatch_get_global_queue(0,0), ^{
- // 汇总结果
- });