GCD 小笔记

下面是学习GCD的一些小笔记,先记下来,到时候忘了还可以再回顾回顾。

Dispatch Async

耗时任务在其它队列异步执行,执行成功后返回到主线程
代码例子:

// background global queue and run the work in the closure asynchronously
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
  guard let self = self else {
    return
  }
  // do some hard thing
  let image = network.fetchImage()
 
  // update ui in main thread
  DispatchQueue.main.async { [weak self] in
    // update main thread imageView image when image downloaded
    self?.imageView.image = image
  }
}

处理读写问题

下面演示了一些单例类处理图片到 添加读取 功能
代码例子:

final class PhotoManager {
    
    /*
     GCD provides an elegant solution of creating a read/write lock
     using dispatch barriers. Dispatch barriers are a group of functions
     acting as a serial-style bottleneck when working with concurrent queues
     
     When you submit a DispatchWorkItem to a dispatch queue you can set flags
     to indicate that it should be the only item executed on the specified
     queue for that particular time. This means that all items submitted to
     the queue prior to the dispatch barrier must complete before the
     DispatchWorkItem will execute.
     
     When the DispatchWorkItem‘s turn arrives, the barrier executes it and
     ensures that the queue does not execute any other tasks during that time.
     Once finished, the queue returns to its default implementation.
     */
    
    private init() {}
    static let shared = PhotoManager()
    
    // create a concurrent queue
    private let concurrentQueue = DispatchQueue(label: "com.zhu.xxxxxxxxxxx", attributes: DispatchQueue.Attributes.concurrent)
   
    private var unsafePhotos: [Photo] = []
    
    // read photos
    var photos: [Photo] {
        var photosCopy: [Photo] = []
        // need photo value, so use sync
        concurrentQueue.sync {
            photosCopy = self.unsafePhotos
        }
        // return the value
        return photosCopy
    }
    
    // add photos
    func addPhoto(_ photo: Photo) {
        // add a barrier to write, act like serial queue now
        concurrentQueue.async(flags: .barrier) { [weak self] in
            guard let self = self else { return }
            
            // add photo
            self.unsafePhotos.append(photo)
            
            // notify main thread
            DispatchQueue.main.async { [weak self] in
                self?.postContentAddedNotification()
            }
        }
    }
}

Dispatch Groups

以下是一个多张图片网络下载的示例

wait() DispatchGroup manages dispatch groups. You’ll first look at its wait method. This blocks your current thread until all the group’s enqueued tasks finish
代码例子:

    func downloadPhotos(withCompletion completion: BatchPhotoDownloadingCompletionClosure?) {
        // async a global queue
        DispatchQueue.global(qos: .userInitiated).async {
            var storedError: NSError?
            
            // a group object
            let downloadGroup = DispatchGroup()
            
            for address in [PhotoURLString.overlyAttachedGirlfriend,
                            PhotoURLString.successKid,
                            PhotoURLString.lotsOfFaces] {
                               
                                // a task start
                                downloadGroup.enter()
                                
                                let url = URL(string: address)
                                let photo = DownloadPhoto(url: url!) { _, error in
                                    if error != nil {
                                        storedError = error
                                    }
                                    // complete that task
                                    downloadGroup.leave()
                                }
                                PhotoManager.shared.addPhoto(photo)
            }
            // will block current thread (use DispatchQueue.global(qos: .userInitiated).async not affect main thread)
            downloadGroup.wait()

            // mission done
            DispatchQueue.main.async {
                completion?(storedError)
            }
        }
    }

但是使用 wait() 会阻塞当前的线程,所以一个更好的方式是使用 notify
代码例子:

    func downloadPhotos(withCompletion completion: BatchPhotoDownloadingCompletionClosure?) {
        var storedError: NSError?
        
        // create a dispathc group
        let downloadGroup = DispatchGroup()
        for address in [PhotoURLString.overlyAttachedGirlfriend,
                        PhotoURLString.successKid,
                        PhotoURLString.lotsOfFaces] {
                            let url = URL(string: address)
                            // start a task
                            downloadGroup.enter()
                            let photo = DownloadPhoto(url: url!) { _, error in
                                if error != nil {
                                    storedError = error
                                }
                                // a task done
                                downloadGroup.leave()
                            }
                            PhotoManager.shared.addPhoto(photo)
        }
        
        // use notify work like asynchronous and not block current thread
        downloadGroup.notify(queue: DispatchQueue.main) {
            completion?(storedError)
        }
    }

任务取消

使用 DispatchWorkItem 模拟任务取消,在代码示例中演示了取消部分图片下载
代码例子:

    func downloadPhotos(withCompletion completion: BatchPhotoDownloadingCompletionClosure?) {
        var storedError: NSError?
        
        // create a dispathc group
        let downloadGroup = DispatchGroup()
        var addresses = PhotoURLString.items
        
        // hold dispatch blocks
        var blocks: [DispatchWorkItem] = []
        
        for index in 0..<addresses.count {
            // start a task
            downloadGroup.enter()
            
            // define the work in closure
            let block = DispatchWorkItem(flags: .inheritQoS) {
                let address = addresses[index]
                let url = URL(string: address)
                let photo = DownloadPhoto(url: url!) { _, error in
                    if error != nil {
                        storedError = error
                    }
                    // a task done
                    downloadGroup.leave()
                }
                PhotoManager.shared.addPhoto(photo)
            }
            blocks.append(block)
            
            // perform task on main thread one by one(help demonstrate cancel task in next)
            DispatchQueue.main.async(execute: block)
        }
        
        // cancel some tasks
        for block in blocks[3..<blocks.count] {
            let cancel = Bool.random()
            if cancel {
                // Cancel block... This can only cancel blocks that are still in a queue and haven't began executing. 
                // You can't cancel a block in the middle of execution.
                block.cancel()
                // remove the canceled block from the dispatch group
                downloadGroup.leave()
            }
        }
        
        // use notify work like asynchronous and not block current thread
        downloadGroup.notify(queue: DispatchQueue.main) {
            completion?(storedError)
        }
    }
参考:

https://www.raywenderlich.com/5370-grand-central-dispatch-tutorial-for-swift-4-part-1-2
https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html
https://developer.apple.com/videos/play/wwdc2016/720/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,271评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,275评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,151评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,550评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,553评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,559评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,924评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,580评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,826评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,578评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,661评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,363评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,940评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,926评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,156评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,872评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,391评论 2 342