Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 如何避免从主线程调用自定义DispatchQueue sync时出现死锁?_Swift_Asynchronous_Grand Central Dispatch - Fatal编程技术网

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链接问题,而不是答案。我的实现似乎与一些答案中的相同