(IOS)学习多线程Dispatch

模拟网络操作的两个方法:

func readTask(label:String){
    print("Start Read \(label)")
    sleep(3)
    print("Finish Read \(label)")
}

func networkTask(label:String, cost:UInt32, complete:@escaping () -> ()){
        print("Start network Task \(label)")
        DispatchQueue.global().async {
        sleep(cost)
        print("End network Task \(label)")
        DispatchQueue.main.async {
            complete()
        }
    }
}

Dispatch

Group:

    let group = DispatchGroup()
    
    group.enter()
    networkTask(label: "1", cost: 2) { 
        group.leave()
    }
    
    group.notify(queue: .main, execute:{
        print("All network is done")
        print("--------------------------------")
    })
    
    group.enter()
    networkTask(label: "2", cost: 4) {
        group.leave()
    }

group.notify用来确保所有任务完成后的操作:
打印结果:


Group.png

Semaphore:

    let semaphore = DispatchSemaphore(value: 2)
    let queue = DispatchQueue(label: "com.leo.concurrentQueue", qos:.default,attributes:.concurrent)
    
    queue.async {
      semaphore.wait()
      self.networkTask(label: "1", cost: 5, complete: {
        semaphore.signal()
        
        print("--------------------------------")
        
      })
    }
    
    queue.async {
        semaphore.wait()
        self.networkTask(label: "2", cost: 2, complete: {
            semaphore.signal()
        })
    }
    
    queue.async {
        semaphore.wait()
        self.networkTask(label: "3", cost: 1, complete: {
            semaphore.signal()
        })
    }

semaphore好比插口,设置Value为2,则最多支持2个任务运行,第3个任务开始需等待其中的某一个任务执行完毕
打印结果:


Semaphore.png

Barrier:

    let concurrentQueue = DispatchQueue(label: "com.leo.concurrentQueue",attributes: .concurrent)

    concurrentQueue.async {
    self.readTask(label: "1")
    }

    concurrentQueue.async {
    self.readTask(label: "2")
    }

   concurrentQueue.async(flags:.barrier, execute: {
        print("Barrier Start")
        sleep(3)
        print("Barrier End")
    })
    
    concurrentQueue.async {
    self.readTask(label: "3")
    print("--------------------------------")
    }

Barrier好比一道屏障,等待之前的任务执行完毕,然后执行flag:.Barrier,完毕后执行后边的任务。
打印结果:


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

推荐阅读更多精彩内容