Skip to content

Instantly share code, notes, and snippets.

@codelynx
Last active November 15, 2016 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codelynx/f004e4046382c4751aa9f35fdf82376f to your computer and use it in GitHub Desktop.
Save codelynx/f004e4046382c4751aa9f35fdf82376f to your computer and use it in GitHub Desktop.
[swift 3] code snippet using GCD's semaphore to protect accessing critical resources from multiple threads where wait and signal may not be the same thread.
class MyObject {
let semaphore = DispatchSemaphore(value: 1)
let session = URLSession(configuration: URLSessionConfiguration.default)
func update1() {
// don't call from mail thread
print("update1 - begin")
semaphore.wait()
let url = URL(string: "https://www.apple.com/")!
let task = self.session.dataTask(with: url) { data, response, error in
defer { self.semaphore.signal() }
// update some critical resources
print("update1 - end")
}
task.resume()
}
func update2() {
// don't call from mail thread
print("update2 - begin")
semaphore.wait()
let url = URL(string: "https://www.apple.com/")!
self.session.dataTask(with: url) { data, response, error in
defer { self.semaphore.signal() }
// update some critical resources
print("update2 - end")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment