GCD(五)-dispatch_apply

这个函数很有意思.
文档注释解释说: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>

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

推荐阅读更多精彩内容

  • 谈到iOS多线程,一般都会谈到四种方式:pthread、NSThread、GCD和NSOperation。其中,苹...
    攻城狮GG阅读 2,312评论 0 3
  • 简介 在iOS中,我们需要将非UI且耗时的任务放在主线程当中执行,同时确保在任务完成时进行回调。常用的三种实现多线...
    adduct阅读 3,003评论 0 1
  • 一. 重点: 1.dispatch_queue_create(生成Dispatch Queue) 2.Main D...
    BestJoker阅读 5,490评论 2 2
  • 基于自 raywenderlich.com 在2015年的两篇文章 Grand Central Dispatch ...
    seedante阅读 5,189评论 0 7
  • 如果我是想炫耀我应该到微博微信QQ等数十个平台可供选择。如果我是假好心为了长脸的话,在我做之前之中之后都肯定会拍照...
    自疗自愈阅读 3,803评论 1 2