Skip to content

Instantly share code, notes, and snippets.

@almaleh
Created January 11, 2020 22:51
Show Gist options
  • Save almaleh/c575c27269983e5ac5e315c6f145ca7a to your computer and use it in GitHub Desktop.
Save almaleh/c575c27269983e5ac5e315c6f145ca7a to your computer and use it in GitHub Desktop.
class ViewController: UIViewController {
let concurrent = DispatchQueue(label: "com.besher.concurrent", attributes: .concurrent)
let isolation = DispatchQueue(label: "com.besher.isolation", attributes: .concurrent)
private var _array = [1,2,3,4,5]
var threadSafeArray: [Int] {
get {
return isolation.sync {
_array
}
}
set {
isolation.async(flags: .barrier) {
self._array = newValue
}
}
}
override func viewDidLoad() {
for _ in 0...15 {
race()
}
}
func race() {
concurrent.async {
for i in self.threadSafeArray {
print(i)
}
}
concurrent.async {
for i in 0..<10 {
self.threadSafeArray.append(i)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment