Skip to content

Instantly share code, notes, and snippets.

@V8tr
Last active July 16, 2018 08:02
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save V8tr/57c7c6a79b51185005862a40d246117d to your computer and use it in GitHub Desktop.
Save V8tr/57c7c6a79b51185005862a40d246117d to your computer and use it in GitHub Desktop.
Atomic property in Swift using Locks. See blog post for more details: http://www.vadimbulavin.com/atomic-properties/
import Foundation
// MARK: - Locks
protocol Lock {
func lock()
func unlock()
}
extension NSLock: Lock {}
final class SpinLock: Lock {
private var unfairLock = os_unfair_lock_s()
func lock() {
os_unfair_lock_lock(&unfairLock)
}
func unlock() {
os_unfair_lock_unlock(&unfairLock)
}
}
final class Mutex: Lock {
private var mutex: pthread_mutex_t = {
var mutex = pthread_mutex_t()
pthread_mutex_init(&mutex, nil)
return mutex
}()
func lock() {
pthread_mutex_lock(&mutex)
}
func unlock() {
pthread_mutex_unlock(&mutex)
}
}
// MARK: - Atomic Property
struct AtomicProperty {
private var underlyingFoo = 0
private let lock: Lock
init(lock: Lock) {
self.lock = lock
}
var foo: Int {
get {
lock.lock()
let value = underlyingFoo
lock.unlock()
return value
}
set {
lock.lock()
underlyingFoo = newValue
lock.unlock()
}
}
}
// MARK: - Usage
let sample = AtomicProperty(lock: SpinLock())
_ = sample.foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment