DispatchGroup sequential execution problem

386 Views Asked by At

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
1

There are 1 best solutions below

1
MobX On

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