GCD之dispatch_group

2020-05-13  本文已影响0人  小羊爱学习

dispatch_group_enter
dispatch_group_leave
dispatch_group_notify
dispatch_group_wait
dispatch_group_enter 和 dispatch_group_leave 一般是成对出现的, 进入一次,就得离开一次。也就是说,当离开和进入的次数相同时,就代表任务组完成了。如果enter比leave多,那就是没完成,如果leave调用的次数多了, 会崩溃的;

- (void)viewDidLoad {
    [super viewDidLoad];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        [self test];
    });
}
- (void)test
{
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    dispatch_group_enter(group);
    NSLog(@"加入");
    NSLog(@"加入");
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    // 异步2秒后离开
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), queue, ^{
        NSLog(@"即将离开 - 1");
        dispatch_group_leave(group);
        NSLog(@"已经离开 - 1");
    });
    
    // 异步3秒后离开
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), queue, ^{
        NSLog(@"即将离开 - 2");
        dispatch_group_leave(group);
        NSLog(@"已经离开 - 2");
    });
    dispatch_group_notify(group, queue, ^{
        NSLog(@"都完成了");
    });
    NSLog(@"开始等待");
    dispatch_group_wait(group, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6 * NSEC_PER_SEC)));
    NSLog(@"等待结束");
}
原文链接:https://blog.csdn.net/pangshishan1/article/details/79611284
1111.png

dispatch_group_wait :在任务组完成时调用,或者任务组超时是调用(完成指的是enter和leave次数一样多)
dispatch_group_notify:不管超不超时,只要任务组完成,会调用,不完成不会调用

上面代码,enter了两次,wait是会阻塞当前线程的,wait时间为6秒, 在6秒内leave了两次, 当最后一次leave的时候,wait就会执行(打开阻塞), 继续往下执行;NSLog(@"已经离开 - 2"); 和NSLog(@"等待结束");是异步进行的;谁先谁后不一定;

上一篇下一篇

猜你喜欢

热点阅读