Ch. 4: Playground not stopping in DispatchGroup.playground

It seems to me that PlaygroundPage.current.finishExecution() is not in the correct place in the code. Because our queues’ work is asynchronous, finishExecution() is being called right after printing “I got tired of waiting” so “End job 1” is not being shown.

If finishExecution() is called instead after “End job 1” (or even removed altogether), “End job 1” is printed 5 seconds afterwards as it should.

PlaygroundPage.current.needsIndefiniteExecution = true

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")
    **PlaygroundPage.current.finishExecution()**
}

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

Thanks, I also ran into this issue.