任务依赖关系如下:
image.png即A、B执行完毕才执行D,以此类推。
先用dispatch_group_create()函数获取3个group;
并行的任务分到一个组,A和B加入g1,B和C加入g2,D和E加入g3;
依赖项(D)利用函数dispatch_group_notify函数等待被依赖项(A, B)所在的group执行完毕。
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_group_t g1 = dispatch_group_create();
dispatch_group_t g2 = dispatch_group_create();
dispatch_group_t g3 = dispatch_group_create();
dispatch_group_enter(g1);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
for(int i = 0; i < 3; i++){
NSLog(@"----A----");
}
dispatch_group_leave(g1);
});
dispatch_group_enter(g1);
dispatch_group_enter(g2);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
for(int i = 0; i < 3; i++){
NSLog(@"----B----");
}
dispatch_group_leave(g1);
dispatch_group_leave(g2);
});
dispatch_group_enter(g2);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
for(int i = 0; i < 3; i++){
NSLog(@"----C----");
}
dispatch_group_leave(g2);
});
dispatch_group_enter(g3);
dispatch_group_notify(g1, dispatch_get_global_queue(0, 0), ^{
for(int i = 0; i < 3; i++){
NSLog(@"----D----");
}
dispatch_group_leave(g3);
});;
dispatch_group_enter(g3);
dispatch_group_notify(g2, dispatch_get_global_queue(0, 0), ^{
for(int i = 0; i < 3; i++){
NSLog(@"----E----");
}
dispatch_group_leave(g3);
});
dispatch_group_notify(g3, dispatch_get_global_queue(0, 0), ^{
for(int i = 0; i < 3; i++){
NSLog(@"----F----");
}
});
}
执行结果如下:
image.png
网友评论