我对DispatchQueue和DispatchSemaphore感到困惑,就像下面的例子一样:
let semaphore : DispatchSemaphore = DispatchSemaphore(value:1)
for i in 1...40 {
DispatchQueue.global().async{
semaphore.wait()
NSLog("......1-%d",i)
semaphore.signal()
}
}
我认为它应该打印1 ... 40,实际上,它只能打印大约25,结果如下:
2016-11-18 19:05:38.786 MyPlayground[7436:495171] ......1-1
2016-11-18 19:05:38.787 MyPlayground[7436:495175] ......1-2
......
2016-11-18 19:05:38.797 MyPlayground[7436:495258] ......1-23
2016-11-18 19:05:38.797 MyPlayground[7436:495244] ......1-24
什么原因?
由于您是异步运行它,因此Playground会在所有40次迭代完成之前完成。将这两行添加到代码的开头或结尾:
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句