美文网首页
dispatch_barrier_async

dispatch_barrier_async

作者: iOS扫地僧 | 来源:发表于2018-03-02 10:34 被阅读0次
    使用实例
    dispatch_queue_t conCurrentQueue = dispatch_queue_create("com.conCurrentQueue", DISPATCH_QUEUE_CONCURRENT);
        dispatch_async(conCurrentQueue, ^{
            NSLog(@"dispatch 1");
        });
        dispatch_async(conCurrentQueue, ^{
            NSLog(@"dispatch 2");
        });
        dispatch_async(conCurrentQueue, ^{
            NSLog(@"dispatch 3");
        });
        dispatch_barrier_async(conCurrentQueue, ^{
            NSLog(@"dispatch barrier");
        });
        dispatch_async(conCurrentQueue, ^{
            for (int i=0; i<3; i++) {
                NSLog(@"dispatch 4");
            }
        });
        dispatch_async(conCurrentQueue, ^{
            for (int i=0; i<3; i++) {
                NSLog(@"dispatch 5");
            }
        });
    
    控制台输出
    2018-03-02 10:23:52.135403+0800 平常测试[7368:1286875] dispatch 1
    2018-03-02 10:23:52.135403+0800 平常测试[7368:1286878] dispatch 2
    2018-03-02 10:23:52.135438+0800 平常测试[7368:1286877] dispatch 3
    2018-03-02 10:23:52.138683+0800 平常测试[7368:1286878] dispatch barrier
    2018-03-02 10:23:52.140115+0800 平常测试[7368:1286878] dispatch 4
    2018-03-02 10:23:52.140128+0800 平常测试[7368:1286885] dispatch 5
    2018-03-02 10:23:52.141160+0800 平常测试[7368:1286885] dispatch 5
    2018-03-02 10:23:52.141173+0800 平常测试[7368:1286878] dispatch 4
    2018-03-02 10:23:52.141662+0800 平常测试[7368:1286878] dispatch 4
    2018-03-02 10:23:52.141662+0800 平常测试[7368:1286885] dispatch 5
    

    dispatch_barrier_async 作用是在并行队列中,等待前面的操作并行操作完成后(也可以理解为阻塞线程,等前面的任务执行完之后去执行后面的任务),然后执行dispatch_barrier_async中的操作,执行完成后,最后该并行队列恢复原有执行状态,继续并行执行(多打印几次可看出是并行执行)

    注意 :dispatch_barrier_async的顺序执行还是依赖queue的类型,必需要queue的类型为dispatch_queue_create创建的,而且attr参数值必需是DISPATCH_QUEUE_CONCURRENT类型,前面非dispatch_barrier_async的类型的执行是依赖其本身的执行时间的,如果attr如果是DISPATCH_QUEUE_SERIAL时,那就完全是符合Serial queue的FIFO特征了。

    相关文章

      网友评论

          本文标题:dispatch_barrier_async

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