简体   繁体   中英

DispatchGroup sequential execution problem

I am trying to implement dispath group, to perform a sequence of operations, that should execute one after another. 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

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"))
      }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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