Last active
July 16, 2018 08:02
-
-
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/
This file contains 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 | |
// 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