简体   繁体   English

迅捷:DispatchGroup死锁

[英]Swift: Deadlock with DispatchGroup

I've got some issue with CoreData concurrency. 我在CoreData并发性方面遇到了一些问题。 I can't do context.perform while a destination thread is blocked with DispatchGroup . 当目标线程被DispatchGroup阻塞时,我无法执行context.perform

Here is a simple example which shows the issue: 这是显示问题的一个简单示例:

func upload(objects: [NSManagedObject]) {
    let group = DispatchGroup()
    for object in objects {
        group.enter()
        upload(object) {
            group.leave()
        }
    }
    group.wait()    // current thread is blocked here

    someAdditionalWorkToDoInSameThread()
}

func upload(object: NSManagedObject, completion: ()->()) {
    let context = object.managedObjectContext
    performAlamofireRequest(object) {
        context.perform {
            // can't reach here because the thread is blocked
            update(object)
            completion()
        }
    }
}

Please, help me to reimplement this properly. 请帮助我正确地重新实现此功能。 Thanks. 谢谢。

Using notify on dispatch group instead of wait, should resolve your issues. 使用通知发送组而不是等待,应该可以解决您的问题。

Calling wait() blocks current thread for completion of previously submitted work. 调用wait()阻止当前线程完成先前提交的工作。
notify(queue:execute:) will notify the queue that you passed as argument that the group task has been completed. notify(queue:execute:)将通知您作为参数传递的队列组任务已完成。

func upload(objects: [NSManagedObject], completion: ()->()) {
    let group = DispatchGroup()
    for object in objects {
        group.enter()
        upload(object) {
            group.leave()
        }
    }
    group.notify(queue: DispatchQueue.main) {
         completion()
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 iOS-Swift 3-DispatchGroup - iOS - swift 3 - DispatchGroup 使用Swift 3中的DispatchGroup()执行任务? - Using DispatchGroup() in Swift 3 to perform a task? Swift 3 DispatchGroup单成功DispatchWorkItem - Swift 3 DispatchGroup single success DispatchWorkItem 无法使DispatchGroup在Swift中正常工作 - Can't get DispatchGroup to work properly in Swift Swift DispatchGroup 在任务完成前通知 - Swift DispatchGroup notify before task finish Swift - 离开 dispatchGroup 时是否需要调用 continue - Swift -is it necessary to call continue when leaving a dispatchGroup 在Swift中使用dispatchGroup处理一系列异步函数时出错 - Error in handling a series of async functions using dispatchGroup in Swift Swift 4 异步调用 for 循环使用 DispatchGroup、DispatchQueue 和 DispatchSemaphore 按顺序执行 - Swift 4 async call with for loop execute in order using DispatchGroup, DispatchQueue and DispatchSemaphore 带有URLSession的Swift iOS -DispatchGroup锁定了未位于其中的应用程序的其他部分 - Swift iOS -DispatchGroup with URLSession is locking other parts of app that it is not located in Swift 中 Firebase 实时数据库观察方法中具有异步函数的 DispatchGroup - DispatchGroup with async functions in a Firebase Realtime DB observe method in Swift
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM