Dispatch Group Question Chapter 3

let group = DispatchGroup()
let queue = DispatchQueue.global(qos: .userInitiated)

queue.async(group: group) {
    print("Start job 1")
    Thread.sleep(until: Date().addingTimeInterval(10))
    print("End job 1")
}

queue.async(group: group) {
    print("Start job 2")
    Thread.sleep(until: Date().addingTimeInterval(2))
    print("End job 2")
}

if group.wait(timeout: .now() + 5) == .timedOut {
    print("I got tired of waiting")
} else {
    print("All the jobs have completed")
} 

the code above is intentional not to include the

group.enter

and

group.leave

on each queue.async?

That’s correct. Because you’re using the queue itself to run the job, and you’re passing the group to it, then it handles the enter/leave calls for you.

1 Like

oh nice, so the queue will handle the enter and leave for me, now I get it, Im already in semaphore and the request is using datatask Im wondering why it is using enter and leave, so in my understanding dataTask doesnt handle enter and leave is that right?

That’s correct. A dataTask doesn’t know anything about your GCD or Operations setups, nor the fact that you’re doing something with groups. That’s why for that you’ve got to do the enter/leave dance yourself.

1 Like