Skip to content

Instantly share code, notes, and snippets.

@serhiybutz
Created September 24, 2021 13:57
Show Gist options
  • Save serhiybutz/6bf8eb8036824542ffad9920daa9325b to your computer and use it in GitHub Desktop.
Save serhiybutz/6bf8eb8036824542ffad9920daa9325b to your computer and use it in GitHub Desktop.
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