为什么这个group.wait总能成功?

时间:2017-09-29 03:48:14

标签: swift grand-central-dispatch

我正试图从group.wait获取超时但这总是成功。

blueGroup.enter()
for i in 1...1000000 {
    print(i)
}
blueGroup.leave()

let time: DispatchTime = .now() + .seconds(1)
let result = blueGroup.wait(timeout: time)

print("finished \(result)") // always success


let redGroup = DispatchGroup()
redGroup.enter()
for i in 0...300000 {
    print(i / (i + 1))
    if i == 300000 {
        print(i)
        let result = redGroup.wait(timeout: .now() + .seconds(10))
        print(result)  // always timeout
        redGroup.leave()
    }
}

哪里错了?

谢谢

1 个答案:

答案 0 :(得分:0)

blueGroup.enter()   // Now the Blue Group will block waiters
for i in 1...1000000 {
   print(i)
}
blueGroup.leave()  // Blue group leaves match enters, so no blocking

let time: DispatchTime = .now() + 0.001
print(time)    
let result = blueGroup.wait(timeout: time) // Nothing blocking, so moving on

print("finished \(result)") // finished success (as expected)

如果你没有完成这个小组,请不要离开。