Skip to content

Instantly share code, notes, and snippets.

@davbeck
Created March 13, 2020 19:53
Show Gist options
  • Save davbeck/1592b206d5a9294d11fa5a9755337ea3 to your computer and use it in GitHub Desktop.
Save davbeck/1592b206d5a9294d11fa5a9755337ea3 to your computer and use it in GitHub Desktop.
struct Lock {
private var unfairLock = os_unfair_lock_s()
mutating func lock(_ work: () -> Void) {
self.lock()
work()
self.unlock()
}
mutating func trylock(_ work: () -> Void) -> Bool {
if self.trylock() {
work()
self.unlock()
return true
} else {
return false
}
}
mutating func lock() {
os_unfair_lock_lock(&unfairLock)
}
mutating func trylock() -> Bool {
os_unfair_lock_trylock(&unfairLock)
}
mutating func unlock() {
os_unfair_lock_unlock(&unfairLock)
}
mutating func assertOwner() {
os_unfair_lock_assert_owner(&unfairLock)
}
mutating func assertNotOwner() {
os_unfair_lock_assert_not_owner(&unfairLock)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment