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
localSharedResourceis wrapped via alocalQueue.syncorlocalQueue.async, then thethreadLockproperty 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
localSharedResourceandlocalQueueis one of them, then thelocalSharedResourceneeds to have additional means of synchronization. Either by anNSLockor by using a dedicated serial queue.E.g.