I have a global variable that is accessed from multiple threads, including from the main thread. I’d like to use NSLock because it’s faster than GCD.
Here’s what I’m trying to do:
struct SynchronizedLock<Value> {
private var _value: Value
private var lock = NSLock()
init(_ value: Value) {
self._value = value
}
var value: Value {
get { lock.synchronized { _value } }
set { lock.synchronized { _value = newValue } }
}
mutating func synchronized<T>(block: (inout Value) throws -> T) rethrows -> T {
return try lock.synchronized {
try block(&_value)
}
}
}
extension NSLocking {
func synchronized<T>(block: () throws -> T) rethrows -> T {
lock()
defer { unlock() }
return try block()
}
}
Would NSLock
block the main thread or is it safe to use on the main thread? Also is this the same situation with DispatchSemaphore
and should resort to queues?