Created
September 5, 2021 08:53
-
-
Save yakushevichsv/b5e8ce2f990bdd877a1ee6821203d4cf to your computer and use it in GitHub Desktop.
os_unfair_lock_t instead of NS{Recursive}Lock
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
// MARK: - UnfairLock | |
final class UnfairLock { | |
private let unfairLock: os_unfair_lock_t //UnsafeMutablePointer<os_unfair_lock> | |
private let unfairValue: os_unfair_lock_s | |
init() { | |
unfairLock = .allocate(capacity: 1) | |
unfairValue = .init() | |
unfairLock.initialize(to: unfairValue) | |
} | |
deinit { | |
unfairLock.deinitialize(count: 1) | |
unfairLock.deallocate() | |
} | |
} | |
// MARK: - NSLocking | |
extension UnfairLock: NSLocking { | |
func lock() { | |
os_unfair_lock_lock(unfairLock) | |
} | |
func tryLock() -> Bool { | |
os_unfair_lock_trylock(unfairLock) | |
} | |
func unlock() { | |
os_unfair_lock_unlock(unfairLock) | |
} | |
} | |
// MARK: - RunInLockTypeProtocol | |
extension UnfairLock: RunInLockTypeProtocol { } | |
// MARK: - RunInLockTypeProtocol | |
protocol RunInLockTypeProtocol { | |
var lockingType: NSLocking { get } | |
func runInLock(_ block: @escaping () -> Void) | |
func runInLock<T>(_ block: @escaping () -> T) -> T | |
} | |
extension RunInLockTypeProtocol { | |
func runInLock<T>(_ block: @escaping () -> T) -> T { | |
lockingType.lock() | |
defer { | |
lockingType.unlock() | |
} | |
return block() | |
} | |
func runInLock(_ block: @escaping () -> Void) { | |
lockingType.lock() | |
defer { | |
lockingType.unlock() | |
} | |
block() | |
} | |
} | |
// MARK: - RunInLockTypeProtocol.NSLocking | |
extension RunInLockTypeProtocol where Self: NSLocking { | |
var lockingType: NSLocking { self } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment