2

我对 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

什么原因?

4

1 回答 1

3

因为您正在异步运行它,所以 Playground 在所有 40 次迭代完成之前完成。将这两行添加到代码的开头或结尾:

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
于 2016-11-18T12:09:15.273 回答