Created
August 18, 2020 08:03
-
-
Save achernoprudov/ba9d1cc80d30bb268674a1d21408d723 to your computer and use it in GitHub Desktop.
Unfair lock implementation
This file contains hidden or 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
| /// 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 fetchLock<T>(block: () throws -> T) rethrows -> T { | |
| lock() | |
| defer { | |
| unlock() | |
| } | |
| return try block() | |
| } | |
| public func lock(block: () throws -> Void) rethrows { | |
| lock() | |
| defer { | |
| unlock() | |
| } | |
| try block() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment