美文网首页
iOS中的GCD(二)

iOS中的GCD(二)

作者: jueyingxx | 来源:发表于2016-10-20 14:32 被阅读32次

dispatch_barrier_async

测试代码:

- (void)test_barrier_async_concurrent_queue {
    
    dispatch_queue_t concurrent_queue = dispatch_queue_create("com.jueyingxx.concurrent_queue", DISPATCH_QUEUE_CONCURRENT);
    
    for (NSInteger i = 0; i < 10; i++) {
        dispatch_async(concurrent_queue, ^{
            NSLog(@"index == %@", @(i));
        });
    }
    
    dispatch_barrier_async(concurrent_queue, ^{
        NSLog(@"barrier is run, %@", [NSThread currentThread]);
    });
    
    NSLog(@"main thread = %@", [NSThread currentThread]);
    
    for (NSInteger i = 10; i < 20; i++) {
        dispatch_async(concurrent_queue, ^{
            NSLog(@"index == %@", @(i));
        });
    }
}

输出结果:

2016-10-25 17:58:16.608 GCD_Demo[14950:9777240] index == 6
2016-10-25 17:58:16.608 GCD_Demo[14950:9777239] index == 5
2016-10-25 17:58:16.608 GCD_Demo[14950:9777221] index == 1
2016-10-25 17:58:16.608 GCD_Demo[14950:9777238] index == 4
2016-10-25 17:58:16.608 GCD_Demo[14950:9777220] index == 0
2016-10-25 17:58:16.608 GCD_Demo[14950:9777241] index == 7
2016-10-25 17:58:16.608 GCD_Demo[14950:9777182] main thread = <NSThread: 0x61000007d640>{number = 1, name = main}
2016-10-25 17:58:16.609 GCD_Demo[14950:9777242] index == 8
2016-10-25 17:58:16.608 GCD_Demo[14950:9777223] index == 2
2016-10-25 17:58:16.608 GCD_Demo[14950:9777237] index == 3
2016-10-25 17:58:16.609 GCD_Demo[14950:9777243] index == 9
2016-10-25 17:58:16.610 GCD_Demo[14950:9777243] barrier is run, <NSThread: 0x608000272cc0>{number = 4, name = (null)}
2016-10-25 17:58:16.610 GCD_Demo[14950:9777237] index == 10
2016-10-25 17:58:16.610 GCD_Demo[14950:9777223] index == 11
2016-10-25 17:58:16.610 GCD_Demo[14950:9777242] index == 12
2016-10-25 17:58:16.610 GCD_Demo[14950:9777241] index == 13
2016-10-25 17:58:16.610 GCD_Demo[14950:9777220] index == 14
2016-10-25 17:58:16.610 GCD_Demo[14950:9777243] index == 16
2016-10-25 17:58:16.610 GCD_Demo[14950:9777221] index == 17
2016-10-25 17:58:16.610 GCD_Demo[14950:9777239] index == 18
2016-10-25 17:58:16.610 GCD_Demo[14950:9777240] index == 19
2016-10-25 17:58:16.611 GCD_Demo[14950:9777238] index == 15

结论:

1、dispatch_async_barrier和dispatch_sync_barrier的唯一区别就是async,会创建新的线程。
2、dispatch_async_barrier,我们可以使用它做这样的需求,就是在同一个并发队列中,我们期望一部分任务先完成,然后再进行后面的任务,或者说后面要执行的任务依赖前面的任务完成。符合这样的情景的我们就应该使用。
3、在串行队列中使用dispatch_async_barrier没有任何意义,因为,在串行队列中的任务本来就是FIFO的。
4、在全局队列中使用dispatch_async_barrier也是没有任何意义的,因为系统每次创建的全局队列有可能都不是同一个队列,所以使用dispatch_async_barrier没有意义。

相关文章

网友评论

      本文标题:iOS中的GCD(二)

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