除了在队列中串行执行任务,iOS还为每一个app默认提供了4个可以并行执行任务的队列,它们叫做concurrent queue。

作为一个队列,concurrent queue中的任务也按照进入队列的顺序“启动”,但是,和serial queue不同,它们不用等待之前的任务完成,iOS会根据系统资源的情况启动多个线程并行执行队列中的任务。
每一个app默认拥有的concurrent queue分成4个不同的优先级,由高到低分别是:
- DISPATCH_QUEUE_PRIORITY_HIGH
- DISPATCH_QUEUE_PRIORITY_DEFAULT
- DISPATCH_QUEUE_PRIORITY_LOW
- DISPATCH_QUEUE_PRIORITY_BACKGROUND
其中,高优先级队列中的任务,会先于低优先级队列中的任务被执行。接下来,我们就把之前在serial queue中下载图片的例子,放到concurrent queue中完成。
使用默认的Concurrent Queue
我们使用dispatch_get_global_queue函数读取系统默认的concurrent queue:
var currQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
其中第一个参数表示我们要获取的队列的优先级。然后,使用dispatch_async把下载任务“派遣”到队列里:
dispatch_async(currQueue, {
let img1 = Downloader.downloadImageWithURL(self.imageUrls[0])
dispatch_async(dispatch_get_main_queue(), {
self.image1.image = img1
self.image1.clipsToBounds = true
})
})
dispatch_async(currQueue, {
let img2 = Downloader.downloadImageWithURL(self.imageUrls[1])
dispatch_async(dispatch_get_main_queue(), {
self.image2.image = img2
self.image2.clipsToBounds = true
})
})
dispatch_async(currQueue, {
let img3 = Downloader.downloadImageWithURL(self.imageUrls[2])
dispatch_async(dispatch_get_main_queue(), {
self.image3.image = img3
self.image3.clipsToBounds = true
})
})
dispatch_async(currQueue, {
let img4 = Downloader.downloadImageWithURL(self.imageUrls[3])
dispatch_async(dispatch_get_main_queue(), {
self.image4.image = img4
self.image4.clipsToBounds = true
})
})
然后Command + R编译执行,就可以看到同一个concurrent queue中所有的任务在并行下载了。
自定义并行队列
除了iOS默认提供的concurrent queue,我们也自己创建处理特定任务的并行队列,这和我们自定义serial queue是类似的:
let currQueue = dispatch_queue_create("com.boxueio.images", DISPATCH_QUEUE_CONCURRENT)
第一个参数表示并行队列的名字,第二参数表示我们要创建一个并行队列。然后Command + R重新编译执行,我们的图片就在自己创建的并行队列中下载了。
网友评论