dispatch_barrier_async的作用

作用

  • 实现高效率的数据库访问和文件访问
  • 避免数据竞争

前提条件

  • 必须使用dispatch_queue_create 创建队列
  • 且队列属性为 DISPATCH_QUEUE_CONCURRENT
    (注意:使用 dispatch_barrier_async,该函数只能搭配自定义并行队列 dispatch_queue_t 使用。不能使用: dispatch_get_global_queue,否则 dispatch_barrier_async 的作用会和 dispatch_async 的作用一模一样。 )
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        NSLog(@"--1---%@",[NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"--2---%@",[NSThread currentThread]);
    });
    dispatch_barrier_async(queue, ^{
        NSLog(@"--barrier---%@",[NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"--3---%@",[NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"--4---%@",[NSThread currentThread]);
    });

结果

2017-06-30 17:34:11.889 test[50672:716568] --1---<NSThread: 0x6080000792c0>{number = 3, name = (null)}
2017-06-30 17:34:11.889 test[50672:716586] --2---<NSThread: 0x600000079f80>{number = 4, name = (null)}
2017-06-30 17:34:11.889 test[50672:716586] --barrier---<NSThread: 0x600000079f80>{number = 4, name = (null)}
2017-06-30 17:34:11.889 test[50672:716586] --3---<NSThread: 0x600000079f80>{number = 4, name = (null)}
2017-06-30 17:34:11.889 test[50672:716568] --4---<NSThread: 0x6080000792c0>{number = 3, name = (null)}

其中 --barrier--- 前的和后的是不确定的,但3,4 一定在1,2 后面执行
参考链接

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在这篇文章中,我将为你整理一下 iOS 开发中几种多线程方案,以及其使用方法和注意事项。当然也会给出几种多线程的案...
    张战威ican阅读 3,754评论 0 0
  • 概述 这篇文章中,我不会说多线程是什么、线程和进程的区别、多线程有什么用,当然我也不会说什么是串行、什么是并行等问...
    hashakey阅读 2,425评论 0 0
  • 文章目录GCD简介任务和队列GCD的使用步骤队列的创建方法任务的创建方法GCD的基本使用并行队列 + 同步执行并行...
    lusen_b阅读 1,761评论 0 1
  • 这下知道为什么像KEEP这样的APP这么受欢迎,因为它作用了观察、分类、定义,三部曲。 它先让用户输入自己的体重身...
    Janet大昕鼓徵阅读 1,495评论 0 7
  • 清明时节 天空若还下着小雨 若你还能来到我坟前 那就请你不要撑着伞 请抬头看着天空 那是我的眼泪 我对你无尽的思念…
    割心的爱阅读 1,274评论 1 1