多线程

作者: _风雨 | 来源:发表于2021-10-21 11:41 被阅读0次

    异步网络请求串行

    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,看个人需求和习惯吧

    相关文章

      网友评论

          本文标题:多线程

          本文链接:https://www.haomeiwen.com/subject/rnsfaltx.html