GCD(五)-dispatch_apply

作者: 司马捷 | 来源:发表于2016-05-26 09:56 被阅读852次

    这个函数很有意思.
    文档注释解释说:Submits a block to a dispatch queue for multiple invocations.
    提交一个block块到一个分发的队里,以供多次调用.

    Discussion 具体说明
    This function submits a block to a dispatch queue for multiple invocations and waits for all iterations of the task block to complete before returning. If the target queue is a concurrent queue returned by dispatch_get_global_queue, the block can be invoked concurrently, and it must therefore be reentrant-safe. Using this function with a concurrent queue can be useful as an efficient parallel for loop.

    这个函数提交代码块到一个分发队列,以供多次调用,会等迭代其中的任务全部完成以后,才会返回.
    如果被提交的队列是并发队列,那么这个代码块必须保证每次读写的安全.
    这个函数对并行的循环 还有作用,

    我理解就是类似遍历一个数组一样,当提交到一个并发的队列上的时候,这个遍历是并发运行的,速度很快.
    看下代码

        let currentQueue:dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
        var array = Array<Int>()
        for index in 0...20 {
            array.append(index)
        }
        print(array.count)
        dispatch_apply(array.count, currentQueue) { (index) in
            sleep(arc4random() % 3) //为了看出并发操作,我们这里的代码进行延时操作.
            let value = array[index]
            print(value)
        }
    

    输出结果:
    <pre>21//这个打印的是数组的个数
    0
    2
    1
    3
    4
    6
    5
    7
    9
    8
    10
    11
    13
    12
    15
    16
    17
    14
    18
    20
    19</pre>

    当提交到一个串行队列上,
    将提交的队列改为:

    let currentQueue:dispatch_queue_t = dispatch_queue_create("com.eric", DISPATCH_QUEUE_SERIAL);
    

    那结果是:
    <pre>0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20</pre>

    相关文章

      网友评论

        本文标题:GCD(五)-dispatch_apply

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