Skip to content

Instantly share code, notes, and snippets.

@davbeck

davbeck/Lock.swift

Created Mar 13, 2020
Embed
What would you like to do?
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