Skip to content

Instantly share code, notes, and snippets.

@Terens777
Created November 10, 2022 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Terens777/0d0eb6fcba8db69117f6b0dbe0d05e9f to your computer and use it in GitHub Desktop.
Save Terens777/0d0eb6fcba8db69117f6b0dbe0d05e9f to your computer and use it in GitHub Desktop.
'os_unfair_lock' is the fastest locking in Swift
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