ios - 在重复的 for 循环中对 dispatch_group_leave() 的不平衡调用

标签 ios concurrency dispatch

我正在使用分派(dispatch)组来获取数据字符串。这是一段代码,我不确定为什么会在这段代码中得到 Unbalanced call to dispatch_group_leave()

var queue = DispatchQueue(label: "extractStringQueue", attributes: .concurrent)
queue.async {
  let m_group = DispatchGroup() 
    let weeks = self.weekDataArray 

    for week in weeks {
        for day in week.dayDataArray {
             m_group.enter()
             day.processStringData(dataName, completionHandler: { (data, response, error) in 
                    if true {
                        // Process 
                        m_group.leave()    
                    }
              })
        }
    }

    m_group.notify(queue: queue, execute: {
     // CompletionHandler
    })
}

最佳答案

两个可能的问题:

问题 1:

processStringData 函数可能会多次调用其 completionHandler,从而导致多次调用 m_group.leave()m_group.leave() 的次数应始终等于 m_group.enter()。如果您尝试 m_group.leave() 的次数超过您进入组的次数,您将收到此错误。

问题 2:

    m_group.enter()
    day.processStringData(dataName, completionHandler: { (data, response, error) in 
    if true {
       // Process 
       m_group.leave()    
    }
})

您的代码仅在 completionHandler 返回 true 时才离开该组,因此如果它返回 false,您将永远不会离开该组。这将导致 m_group.notify 永远不会触发,即使一旦完成 block 返回 false 并不必要地永远阻塞线程。

你应该做的是

    m_group.enter()
    day.processStringData(dataName, completionHandler: { (data, response, error) in 
    if true {
       // Process    
    }
    m_group.leave() 
})

问题 3:

确保 processStringData 在执行完成 block 之前没有改变线程。切换回主线程并执行完成 block 是一种常见的做法。使用不同的线程进入 dispatch_group 并试图从完全不同的线程离开该组也会导致不平衡调用离开。

关于ios - 在重复的 for 循环中对 dispatch_group_leave() 的不平衡调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44772052/

相关文章:

ios - 协议(protocol)的 Swift 实例

ios - 我可以做什么,无论是将图像添加到 Assets 还是在 ios 中的文件夹中

java - 什么时候调用 java 的 thread.run() 而不是 thread.start()?

objective-c - 当 tabBarController/navController 在同一应用程序中时推送到详细 View 时出现问题

multithreading - 如何在线程之间共享非发送对象?

go - 了解 golang channel 。所有的goroutines都睡着了——死锁【围棋之旅,爬虫】

javascript - 在另一个 Action 之后 react Redux 调度 Action

Objective-C错误: no viable overloaded =

objective-c - 分派(dispatch)到主队列总是失败

ios - 如何在 Swift 3 中显示当前位置图标?