Skip to content

Instantly share code, notes, and snippets.

@waltflanagan
Last active September 20, 2016 14:37
Show Gist options
  • Save waltflanagan/c700e0099d012823f37e1a5e2ad95d9f to your computer and use it in GitHub Desktop.
Save waltflanagan/c700e0099d012823f37e1a5e2ad95d9f to your computer and use it in GitHub Desktop.
public class AtomicProperty<T:Any> {
private var mutex: pthread_mutex_t = {
var mutex = pthread_mutex_t()
pthread_mutex_init(&mutex, nil)
return mutex
}()
private var _value: T
public var value: T {
get {
pthread_mutex_lock(&mutex)
defer { pthread_mutex_unlock(&mutex) }
return _value
}
set {
pthread_mutex_lock(&mutex)
self._value = newValue
pthread_mutex_unlock(&mutex)
}
}
public func mutate(with: (inout T) -> Void ) {
pthread_mutex_lock(&mutex)
with(&_value)
pthread_mutex_unlock(&mutex)
}
public init(initialValue: T) { _value = initialValue }
}
var ap = AtomicProperty(initialValue: [String:String]() )
ap.mutate { $0["asdf"] = "asdf" }
ap.value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment