Skip to content

Instantly share code, notes, and snippets.

@Jimmy-Prime
Created October 22, 2021 09:49
Show Gist options
  • Save Jimmy-Prime/a22114f1a2f42ecd234f6429e0887413 to your computer and use it in GitHub Desktop.
Save Jimmy-Prime/a22114f1a2f42ecd234f6429e0887413 to your computer and use it in GitHub Desktop.
class OAO {
let concurrent = DispatchQueue(label: "OAO", attributes: .concurrent)
let arrayQueue = DispatchQueue(label: "OAO.array", attributes: .concurrent)
// Thread-Safe
private var _array: [Int] = []
private var array: [Int] {
get {
arrayQueue.sync {
_array
}
}
set {
arrayQueue.async(flags: .barrier) {
self._array = newValue
}
}
}
// Not-Thread-Safe
// private var array: [Int] = []
func test() {
concurrent.async {
print(self.array)
}
concurrent.async {
self.array = [1, 2, 3]
}
concurrent.async {
print(self.array)
}
concurrent.async {
self.array = [100, 10, 1]
}
concurrent.async {
print(self.array)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment