这取决于。
如果所有访问localSharedResource
都通过localQueue.sync
or包装localQueue.async
,则threadLock
可以删除该属性。串行队列 ( localQueue
) 已经在进行所有必要的同步。上式可以改写为:
class Factory {
var localSharedResource
var localQueue = DispatchQueue(label: "localQueue")
func modify(){
localQueue.async {
localSharedResource = "a change is made here"
}
}
}
然而,如果有多个线程可能访问localSharedResource
并且localQueue
是其中之一,那么localSharedResource
需要有额外的同步方式。通过NSLock
或使用专用串行队列。
例如
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()
}
}
func modifyAgain() {
DispatchQueue.global().async {
self.threadLock.lock()
localSharedResource = "another change"
self.threadLock.unlock()
}
}
}