Last active
December 13, 2021 12:08
-
-
Save bradleymackey/40cc8dfde211b6b0cbfcdb5a4505da3d to your computer and use it in GitHub Desktop.
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
/// An efficient lock to prevent contesting access to a resource across threads | |
/// | |
/// This is a very thin wrapper around `os_unfair_lock` with a better Swift interface. | |
/// It also has a similar interface to `NSLock` | |
public final class Lock: @unchecked Sendable { | |
@usableFromInline | |
var _mutex = os_unfair_lock() | |
public init() { } | |
} | |
extension Lock { | |
/// Locks the `Lock`. Blocks if it is already locked. | |
@inlinable | |
public func lock() { | |
os_unfair_lock_lock(&_mutex) | |
} | |
/// Unlocks the `Lock`. | |
@inlinable | |
public func unlock() { | |
os_unfair_lock_unlock(&_mutex) | |
} | |
/// Locks the `Lock` if it is not already locked. | |
/// | |
/// It is invalid to call this in a retry loop. | |
/// The program must be able to proceed without having aquired the lock. | |
@inlinable | |
public func `try`() -> Bool { | |
os_unfair_lock_trylock(&_mutex) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment