Created
July 14, 2018 07:15
-
-
Save V8tr/5d079c49693d62b75e0885d686806f6e to your computer and use it in GitHub Desktop.
Atomic property in Swift using ReadWriteLock. See blog post for more details: http://www.vadimbulavin.com/atomic-properties/
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
final class ReadWriteLock { | |
private var rwlock: pthread_rwlock_t = { | |
var rwlock = pthread_rwlock_t() | |
pthread_rwlock_init(&rwlock, nil) | |
return rwlock | |
}() | |
func writeLock() { | |
pthread_rwlock_wrlock(&rwlock) | |
} | |
func readLock() { | |
pthread_rwlock_rdlock(&rwlock) | |
} | |
func unlock() { | |
pthread_rwlock_unlock(&rwlock) | |
} | |
} | |
class ReadWriteLockAtomicProperty { | |
private var underlyingFoo = 0 | |
private let lock = ReadWriteLock() | |
var foo: Int { | |
get { | |
lock.readLock() | |
let value = underlyingFoo | |
lock.unlock() | |
return value | |
} | |
set { | |
lock.writeLock() | |
underlyingFoo = newValue | |
lock.unlock() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment