Skip to content

Instantly share code, notes, and snippets.

@xxKRASHxx
Created December 8, 2017 07:55
Show Gist options
  • Save xxKRASHxx/00b100c1634141677bba0773f819761c to your computer and use it in GitHub Desktop.
Save xxKRASHxx/00b100c1634141677bba0773f819761c to your computer and use it in GitHub Desktop.
import Foundation
/// Protocol for NSLocking objects that also provide tryLock()
public protocol TryLockable: NSLocking {
func `try`() -> Bool
}
// These Cocoa classes have tryLock()
extension NSLock: TryLockable {}
extension NSRecursiveLock: TryLockable {}
extension NSConditionLock: TryLockable {}
/// Protocol for NSLocking objects that also provide lockBeforeDate()
public protocol BeforeDateLockable: NSLocking {
func lock(before limit: Date) -> Bool
}
// These Cocoa classes have lockBeforeDate()
extension NSLock: BeforeDateLockable {}
extension NSRecursiveLock: BeforeDateLockable {}
extension NSConditionLock: BeforeDateLockable {}
func synchronize<L: NSLocking, T>(sync: L, action: () throws -> T ) rethrows -> T {
sync.lock()
defer { sync.unlock() }
return try action()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment