Skip to content

Instantly share code, notes, and snippets.

@hannesoid
Last active December 3, 2019 11:24
Show Gist options
  • Save hannesoid/cacbe6f18af4fe380065dd8bea05b5a5 to your computer and use it in GitHub Desktop.
Save hannesoid/cacbe6f18af4fe380065dd8bea05b5a5 to your computer and use it in GitHub Desktop.
Atomically locking property wrapper for swift
//
// Locked.swift
//
//
// Created by Hannes Oud on 29.11.19.
// Helpful reading https://www.vadimbulavin.com/swift-atomic-properties-with-property-wrappers/
import Foundation
/// Atomically locks a property using `os_unfair_lock`
@propertyWrapper
public struct Locked<Value> {
private var value: Value
private let lock = UnfairLock()
public init(wrappedValue value: Value) {
self.value = value
}
public var wrappedValue: Value {
get { return load() }
set { store(newValue: newValue) }
}
}
private extension Locked {
func load() -> Value {
lock.lock()
defer { lock.unlock() }
return value
}
mutating func store(newValue: Value) {
lock.lock()
defer { lock.unlock() }
value = newValue
}
}
private final class UnfairLock {
private var _lock = os_unfair_lock()
func lock() { os_unfair_lock_lock(&_lock) }
func locked() -> Bool { return os_unfair_lock_trylock(&_lock) }
func unlock() { os_unfair_lock_unlock(&_lock) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment