美文网首页
iOS dispatch_group_enter建立任务的依赖关

iOS dispatch_group_enter建立任务的依赖关

作者: KingWorld | 来源:发表于2021-04-19 13:08 被阅读0次

任务依赖关系如下:

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

相关文章

网友评论

      本文标题:iOS dispatch_group_enter建立任务的依赖关

      本文链接:https://www.haomeiwen.com/subject/flpelltx.html