多线程

异步网络请求串行

let group = DispatchGroup()
//    let queue = DispatchQueue(label: "current", attributes: .concurrent)
    let queue = DispatchQueue(label: "current")
    let sema = DispatchSemaphore(value: 0)

func test() {
        queue.async(group: group) {
            DispatchQueue.delay(2) {
                print("1")
                self.sema.signal()
            }
            print("1 ----")
            
            _ = self.sema.wait(timeout: .distantFuture)
        }
        
        queue.async(group: group) {
            DispatchQueue.delay(1) {
                print("2")
                self.sema.signal()
            }
            print("2 ----")
            
            _ = self.sema.wait(timeout: .distantFuture)
        }
        
        
        queue.async(group: group) {
            DispatchQueue.delay(2) {
                print("3")
                self.sema.signal()
            }
            print("3 ----")
            
            _ = self.sema.wait(timeout: .distantFuture)
        }
        
        group.notify(queue: queue) {
            print("finish")
        }
    }

DispatchSemaphore初始值为1

let group = DispatchGroup()
    let queue = DispatchQueue(label: "current")
    let sema = DispatchSemaphore(value: 1)

func test() {
        
        queue.async(group: group) {
            _ = self.sema.wait(timeout: .distantFuture)
            
            DispatchQueue.delay(2) {
                print("1")
                self.sema.signal()
            }
            print("1 ----")
        }

        
        
        queue.async(group: group) {
            _ = self.sema.wait(timeout: .distantFuture)
            
            DispatchQueue.delay(1) {
                print("2")
                self.sema.signal()
            }
            print("2 ----")
        }

        
        queue.async(group: group) {
            _ = self.sema.wait(timeout: .distantFuture)
            
            DispatchQueue.delay(2) {
                print("3")
                self.sema.signal()
            }
            print("3 ----")
        }

        group.notify(queue: queue) {
            _ = self.sema.wait(timeout: .distantFuture)
            
            print("finish")
        }
    }

DispatchSemaphore初始值为0还是1,看个人需求和习惯吧

你可能感兴趣的:(多线程)