Created
November 10, 2022 20:44
-
-
Save Terens777/0d0eb6fcba8db69117f6b0dbe0d05e9f to your computer and use it in GitHub Desktop.
'os_unfair_lock' is the fastest locking in 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
final class UnfairLock { | |
private var _lock: UnsafeMutablePointer<os_unfair_lock> | |
init() { | |
_lock = UnsafeMutablePointer<os_unfair_lock>.allocate(capacity: 1) | |
_lock.initialize(to: os_unfair_lock()) | |
} | |
deinit { | |
_lock.deallocate() | |
} | |
func locked<ReturnValue>( | |
_ f: () throws -> ReturnValue | |
) rethrows -> ReturnValue { | |
os_unfair_lock_lock(_lock) | |
defer { os_unfair_lock_unlock(_lock) } | |
return try f() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment