简体   繁体   English

DispatchGroup顺序执行问题

[英]DispatchGroup sequential execution problem

I am trying to implement dispath group, to perform a sequence of operations, that should execute one after another.我正在尝试实现 dispath 组,以执行一系列操作,这些操作应该一个接一个地执行。 But the issue is all the tasks adding to the group are executing in parallel.但问题是添加到组中的所有任务都是并行执行的。 Please share your thoughts, following is the sample I am trying.请分享您的想法,以下是我正在尝试的示例。

    let group = DispatchGroup()
    
    group.enter()
    print("Enter Activity One")
    self.performActivityOne(param: []) {
        group.leave()
        print("leave 1")
    }
    
    group.enter()
    print("Enter Activity two")
    self. self.performActivityTwo(param: []) {
        group.leave()
        print("leave 2")
    }
    
    group.notify(queue: DispatchQueue.main) {
        // This block will be executed once all above threads completed and call dispatch_group_leave
        print("Prepare completed. I'm readyyyy")
    }

The output I am getting is我得到的 output 是

Enter Activity One
Enter Activity two
leave 2

Thanks for all the support and valuable comments, I fixed the issue by using Semaphores:感谢所有支持和宝贵意见,我使用信号量解决了这个问题:

let semaphore = DispatchSemaphore(value: 1)
    DispatchQueue.global(qos: .userInitiated).async {
         let dispatchGroup = DispatchGroup()

         dispatchGroup.enter()
        semaphore.wait()
        self.performActivityOne(param: []) {
            dispatchGroup.leave()
            print("leave")
            semaphore.signal()
        }
        
        dispatchGroup.enter()
        semaphore.wait()
        self. self.performActivityTwo(param: []) {
            dispatchGroup.leave()
            print("leave 2")
            semaphore.signal()
        }
        
    dispatchGroup.wait()
      DispatchQueue.main.async {
         print("Completed all"))
      }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM