Skip to content

Instantly share code, notes, and snippets.

@achernoprudov
Created March 12, 2021 06:31
Show Gist options
  • Save achernoprudov/6fc4ae734051630bee3a53fa171c4574 to your computer and use it in GitHub Desktop.
Save achernoprudov/6fc4ae734051630bee3a53fa171c4574 to your computer and use it in GitHub Desktop.
Unfair lock swift wrapper
/// Low-level lock that allows waiters to block efficiently on contention.
///
/// Based on `os_unfair_lock_s`
public class UnfairLock {
// MARK: - Instance variables
private var unfairLock = os_unfair_lock_s()
// MARK: - Public
public init() {
}
public func lock() {
os_unfair_lock_lock(&unfairLock)
}
public func unlock() {
os_unfair_lock_unlock(&unfairLock)
}
public func lock<T>(block: () throws -> T) rethrows -> T {
lock()
defer {
unlock()
}
return try block()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment