Skip to content

Instantly share code, notes, and snippets.

@standinga
Last active August 17, 2019 13:30
Show Gist options
  • Save standinga/7ec78873621c0edcd12236f19419d463 to your computer and use it in GitHub Desktop.
Save standinga/7ec78873621c0edcd12236f19419d463 to your computer and use it in GitHub Desktop.
Final solution for medium post about DispatchGroup and DispatchSemaphore synchronization
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