2016-11-18 5 views
2

Je suis confondu avec DispatchQueue et DispatchSemaphore.Like l'exemple suivant:[Playground] La relation bettwen DispatchQueue et DispatchSemaphore

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

Je pense qu'il devrait imprimer 1 ... 40, en fait, il imprime seulement 25 , le résultat comme le suivant:

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 

Qui sait la raison?

Merci

Répondre

2

Parce que vous utilisez ce async, termine Playground avant les 40 itérations sont terminées. Ajoutez ces 2 lignes au début ou à la fin de votre code:

import PlaygroundSupport 
PlaygroundPage.current.needsIndefiniteExecution = true