Last active
September 20, 2016 14:37
-
-
Save waltflanagan/c700e0099d012823f37e1a5e2ad95d9f 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
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