(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,完毕后执行后边的任务。
打印结果:


(IOS)学习多线程Dispatch_第1张图片
Barrier.png

你可能感兴趣的:((IOS)学习多线程Dispatch)