简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM