dispatch_barrier_sync 和dispatch_

作者: 红成魔 | 来源:发表于2016-09-27 10:20 被阅读1109次

    需求:有4个任务{1,2,3,4},执行完前2个再执行后2个

    这里我们用到栅栏函数dispatch_barrier_(a)sync,(也可以用队列组),我们要注意的是不能使用全局并发队列(系统提供给我们的)否则会散失栅栏函数的意义

    区别:先看官方文档

    dispatch_barrier_sync: Submits a barrier block object for execution and waits until that block completes.(提交一个栅栏函数在执行中,它会等待栅栏函数执行完)

    dispatch_barrier_async: Submits a barrier block for asynchronous execution and returns immediately.(提交一个栅栏函数在异步执行中,它会立马返回)

    作者理解:dispatch_barrier_sync 需要等待栅栏执行完才会执行栅栏后面的任务,而dispatch_barrier_async 无需等待栅栏执行完,会继续往下走(保留在队列里)

    原因:在同步栅栏时栅栏函数在主线程中执行,而异步栅栏中开辟了子线程栅栏函数在子线程中执行

    1.先来看看dispatch_barrier_sync

    dispatch_barrier_sync

    打印:

    dispatch_barrier_sync第一次打印

    再次打印:

    dispatch_barrier_sync第二次打印

    得到结果:栅栏函数确实分割了任务,但是任务执行的顺序的确是无序的(异步函数)

    2.换成dispatch_barrier_async

    dispatch_barrier_async

    打印:

    再次打印:

    特别注意:

    The queue you specify should be a concurrent queue that you create yourself using the dispatch_queue_create function. If the queue you pass to this function is a serial queue or one of the global concurrent queues, this function behaves like the dispatch_sync function.

    官方说明大意:在使用栅栏函数时.使用自定义队列才有意义,如果用的是串行队列或者系统提供的全局并发队列,这个栅栏函数的作用等同于一个同步函数的作用

    相关文章

      网友评论

      • lenolee:最后一点:针对dispatch_barrier_sync 如果你传入的是串行或全局并发队列 则它的作用和 dispatch_sync 一样; 如果是 dispatch_barrier_async 则它的作用和 dispatch_async一样
        Easyin:还有个疑问,为什么dispatch_barrier_async用全局并发队列就会变成跟dispatch_sync 一样呢?
        红成魔:@lenolee 实际开发中 用到不多:stuck_out_tongue:以后多多交流

      本文标题:dispatch_barrier_sync 和dispatch_

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