【问题标题】:Playground - The relationship between DispatchQueue and DispatchSemaphorePlayground - DispatchQueue 和 DispatchSemaphore 的关系
【发布时间】:2016-11-18 11:11:51
【问题描述】:

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

什么原因?

【问题讨论】:

    标签: ios swift semaphore dispatch gdc


    【解决方案1】:

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

    import PlaygroundSupport
    PlaygroundPage.current.needsIndefiniteExecution = true
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      • 1970-01-01
      • 2021-04-28
      • 2019-09-22
      • 1970-01-01
      • 2017-07-17
      • 1970-01-01
      相关资源
      最近更新 更多