I have the following 2 thread safe wrappers implementation for a boolean:
1 - Using NSLock
class ThreadSafeBool {
private let lock = NSLock()
private var wrappedValue: Bool
var value: Bool {
get {
lock.lock()
defer { lock.unlock() }
return wrappedValue
}
set {
lock.lock()
defer { lock.unlock() }
wrappedValue = newValue
}
}
init(_ initialValue: Bool) {
wrappedValue = initialValue
}
}
2 - Using DispatchQueue and sync
class ThreadSafeBoolQueue {
private let queue = DispatchQueue(label: "my.queue")
private var wrappedValue: Bool
var value: Bool {
get {
self.queue.sync { return wrappedValue }
}
set {
self.queue.sync { wrappedValue = newValue }
}
}
init(_ initialValue: Bool) {
wrappedValue = initialValue
}
}
Even though the NSLock it is much more faster then the sync queues, os_unfair_lock
is even faster.
Could someone please let me know why in lots of example is prefer the second locking mode, including Apple presentation?
PS: Please keep in mind that the classes are just examples, so the main question is why queue over NSLock/os_unfair_lock?
Thank you very much