Dry up lock / unlock logic in Lock.swift

This commit is contained in:
Nicholas Maccharoli 2016-04-25 03:10:06 +09:00
parent 7133d6a6e5
commit 9e345e3645
1 changed files with 8 additions and 20 deletions

View File

@ -37,23 +37,17 @@ protocol Lock {
}
func performLocked(@noescape action: () -> Void) {
pthread_spin_lock(&_lock)
lock(); defer { unlock() }
action()
pthread_spin_unlock(&_lock)
}
func calculateLocked<T>(@noescape action: () -> T) -> T {
pthread_spin_lock(&_lock)
let result = action()
pthread_spin_unlock(&_lock)
return result
lock(); defer { unlock() }
return action()
}
func calculateLockedOrFail<T>(@noescape action: () throws -> T) throws -> T {
pthread_spin_lock(&_lock)
defer {
pthread_spin_unlock(&_lock)
}
lock(); defer { unlock() }
let result = try action()
return result
}
@ -70,23 +64,17 @@ protocol Lock {
extension NSRecursiveLock : Lock {
func performLocked(@noescape action: () -> Void) {
self.lock()
lock(); defer { unlock() }
action()
self.unlock()
}
func calculateLocked<T>(@noescape action: () -> T) -> T {
self.lock()
let result = action()
self.unlock()
return result
lock(); defer { unlock() }
return action()
}
func calculateLockedOrFail<T>(@noescape action: () throws -> T) throws -> T {
self.lock()
defer {
self.unlock()
}
lock(); defer { unlock() }
let result = try action()
return result
}