Last active
March 3, 2017 19:23
-
-
Save msanders/7038230d72b8916979c8a8cf3a3dd620 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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