Swift 如何避免从主线程调用自定义DispatchQueue sync时出现死锁?
我正在尝试从多个线程安全地读/写数据,如下所述: 下面是我如何读取数据的一个片段Swift 如何避免从主线程调用自定义DispatchQueue sync时出现死锁?,swift,asynchronous,grand-central-dispatch,Swift,Asynchronous,Grand Central Dispatch,我正在尝试从多个线程安全地读/写数据,如下所述: 下面是我如何读取数据的一个片段 private let annotationsQueue = DispatchQueue(label: "myCustoLabel", attributes: .concurrent) private var unsafeAnnotations = [MapAnnotation]() private var annotations: [MapAnnotation] {
private let annotationsQueue = DispatchQueue(label: "myCustoLabel", attributes: .concurrent)
private var unsafeAnnotations = [MapAnnotation]()
private var annotations: [MapAnnotation] {
var annotationsCopy: [MapAnnotation]!
annotationsQueue.sync {
annotationsCopy = self.unsafeAnnotations
}
return annotationsCopy
}
我的问题是,annotations
有时会从DispatchQueue.main.async
调用,这会导致死锁
这是我到达死锁时堆栈跟踪的屏幕截图
我的问题是,我应该如何处理这种情况?我是否应该强制我的注释queue
在后台线程上运行?
或者我应该编写我的代码,这样就永远不会从
DispatchQueue.main.async
?调用注释,因为创建并发队列时,可以使用dispatch barrier从多个线程读/写
private let annotationsQueue = DispatchQueue(label: "myCustoLabel", attributes: .concurrent)
private var unsafeAnnotations = [MapAnnotation]()
private var annotations: [MapAnnotation]? {
var annotationsCopy: [MapAnnotation]!
get {
annotationsQueue.sync {
return annotationsCopy
}
return nil
}
set {
annotationsQueue.async(flag: .barrier) {
annotationsCopy = self.unsafeAnnotations
}
}
}
这里您可以阅读一些注释数据。对吧?annotationsquee.sync
@JatinRB是的,我添加了屏幕截图以突出显示问题出于某种原因低优先级任务它将不起作用,因此请尝试像这样非常简单的getter setter方法。不要使用sync
@JatinRB链接问题,而不是答案。我的实现似乎与一些答案中的相同