Last active
August 17, 2019 13:30
-
-
Save standinga/7ec78873621c0edcd12236f19419d463 to your computer and use it in GitHub Desktop.
Final solution for medium post about DispatchGroup and DispatchSemaphore synchronization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
func fetchData(_ data: Int, delay: Double, completionHandler: @escaping (String)->()) { | |
DispatchQueue.main.asyncAfter(deadline: .now() + delay) { | |
completionHandler("\(data)") | |
} | |
} | |
DispatchQueue.global().async { | |
let semaphore = DispatchSemaphore(value: 0) | |
var text = "" | |
for i in 0..<20 { | |
fetchData(i, delay: Double.random(in: 0...0.2)) { | |
text += "\($0) - " | |
semaphore.signal() | |
} | |
semaphore.wait() | |
} | |
print(text) | |
exit(0) | |
} | |
RunLoop.current.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment