iosswiftsemaphoredispatchgdc

Playground - The relationship between DispatchQueue and DispatchSemaphore


I am confused with DispatchQueue and DispatchSemaphore.Like the following example:

let semaphore : DispatchSemaphore = DispatchSemaphore(value:1)
for i in 1...40 {
    DispatchQueue.global().async{
        semaphore.wait()
        NSLog("......1-%d",i)
        semaphore.signal()
    }
}

I think it should print 1...40,actually, it only prints about 25, the result like the following:

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

What's the reason?


Solution

  • Because you are running it async, Playground finishes before all 40 iterations are complete. Add these 2 lines to the beginning or end of your code:

    import PlaygroundSupport
    PlaygroundPage.current.needsIndefiniteExecution = true