class Factory {
var localSharedResource
var localQueue = DispatchQueue(label: "localQueue")
let threadLock = NSLock()
func modify(){
localQueue.async {
self.threadLock.lock()
localSharedResource = "a change is made here"
self.threadLock.unlock()
}
}
}
Should I use lock if localSharedResource is accessed by other threads too?
It depends.
If all access to
localSharedResource
is wrapped via alocalQueue.sync
orlocalQueue.async
, then thethreadLock
property can be removed. The serial queue (localQueue
) is already doing all the necessary synchronization. The above could be rewritten as:If however there are multiple threads potentially accessing the
localSharedResource
andlocalQueue
is one of them, then thelocalSharedResource
needs to have additional means of synchronization. Either by anNSLock
or by using a dedicated serial queue.E.g.