Skip to content

Instantly share code, notes, and snippets.

@msanders
Last active March 3, 2017 19:23
Show Gist options
  • Save msanders/7038230d72b8916979c8a8cf3a3dd620 to your computer and use it in GitHub Desktop.
Save msanders/7038230d72b8916979c8a8cf3a3dd620 to your computer and use it in GitHub Desktop.
import Foundation
final class GCDLock<Value> {
var value: Value
let queue = DispatchQueue(label: "")
init(value: Value) {
self.value = value
}
func read() -> Value {
var value: Value?
queue.sync {
value = self.value
}
return value!
}
func write(_ newValue: Value) {
queue.async {
self.value = newValue
}
}
}
// Example use case
final class Example {
private var counterLock: GCDLock<Int> = GCDLock(value: 0)
var counter: Int {
get { return counterLock.read() }
set { counterLock.write(newValue) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment