Last active
February 19, 2021 10:55
-
-
Save geor-kasapidi/6cb13f53554147b6ced3175640048adc to your computer and use it in GitHub Desktop.
OSUnfairLock Swift
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
private final class OSUnfairLock { | |
private let pointer: os_unfair_lock_t | |
init() { | |
self.pointer = .allocate(capacity: 1) | |
self.pointer.initialize(to: os_unfair_lock()) | |
} | |
deinit { | |
self.pointer.deinitialize(count: 1) | |
self.pointer.deallocate() | |
} | |
func lock() { | |
os_unfair_lock_lock(self.pointer) | |
} | |
func unlock() { | |
os_unfair_lock_unlock(self.pointer) | |
} | |
} | |
final class ThreadSafe<T> { | |
private let lock = OSUnfairLock() | |
private var _value: T | |
init(_ value: T) { | |
self._value = value | |
} | |
var value: T { | |
self.lock.lock(); defer { self.lock.unlock() } | |
return self._value | |
} | |
@discardableResult | |
func mutate<U>(_ action: (inout T) -> U) -> U { | |
self.lock.lock(); defer { self.lock.unlock() } | |
return action(&self._value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment