Created
September 24, 2021 13:57
-
-
Save serhiybutz/6bf8eb8036824542ffad9920daa9325b to your computer and use it in GitHub Desktop.
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
public final class SharedManager { | |
private var registry = Registry() | |
private let mutex = NSLock() | |
internal func internalBorrow(_ props: [AnyObject], accessBlock: () -> Void) { | |
let active = activateBorrowingFor(props) | |
defer { | |
deactivateBorrowing(active) | |
active.revoke() | |
} | |
accessBlock() | |
} | |
private func activateBorrowingFor(_ props: [AnyObject]) -> Borrowing { | |
while true { | |
mutex.lock() | |
let preservedRegistry = registry | |
mutex.unlock() | |
let new = Borrowing(props) | |
if let blockingBorrowing = preservedRegistry.searchForConflictingBorrowingWith(new) { | |
blockingBorrowing.wait() | |
} | |
mutex.lock() | |
defer { mutex.unlock() } | |
if registry !== preservedRegistry { | |
continue | |
} | |
registry = registry.copyWithAdded(new) | |
return new // bail out | |
} | |
} | |
private func deactivateBorrowing(_ borrowing: Borrowing) { | |
mutex.lock() | |
defer { mutex.unlock() } | |
registry = registry.copyWithRemoved(borrowing) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment