Last active
November 15, 2016 16:27
-
-
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.
This file contains 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
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