1

This is different than wanting to stop after a period of time. An example of possible use case:

func calculate(_ nums: [Int], _ target: Int, completion: @escaping (([Int]) -> Void)) {
        let enumerated = nums.enumerated()
        let queue = DispatchQueue.global(qos: .default)
        let group = DispatchGroup()
        var answer: [Int] = []
        queue.async { () -> Void in
            for (xIndex, xElement) in nums.enumerated() {
                queue.async(group: group) {
                    for (yIndex, yElement) in enumerated where yIndex != xIndex {
                        if xElement + yElement == target {
                            answer = [xIndex, yIndex]
                            //I want it to end here
                        }
                    }
                }
            }
            group.notify(queue: queue) {
                completion(answer)
            }
        }
    }

Here I am attaching each of the inner for loop to the dispatch group so they are calculating at the same time, but when the answer is found let's say in the 3rd for run, there is no need for the Dispatch group to calculate others and should stop like all the tasks are completed and call group.notify

Basically I want it to return when it reaches the answer. Is there any way to do this? if so how?

From what I've researched, we can use group.leave to explicitly say that a block in the group finished executing, but how can it be done so all the blocks in the group finish when we reach the desired point?

shadow of arman
  • 395
  • 1
  • 7
  • 16
  • I used `group.suspend()` in my example and had it print the `answer` before it, it printed twice, so I think it's still not stopping *all* the executions. or am I doing something wrong here and need to study it more? – shadow of arman Mar 24 '21 at 07:59
  • Have you thought about using NSOperation, break the work into Operations, when first one of them succeeds, cancel them all. Be sure to check for cancellation in the operation. – Shadowrun Mar 24 '21 at 09:58
  • No, didn't know about NSOperation, and if it does work it that's awesome and thanks for pointing it out! but still, I would like to know if it can be accomplished with `DispatchGroup` – shadow of arman Mar 24 '21 at 17:43
  • NSOperation is built on top of GCD, so you could build your own 'operation' abstraction on top of GCD too, but it's not trivial to implement. – Shadowrun Mar 25 '21 at 09:03

0 Answers0