[英]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.