Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispatch group - cannot notify to main thread

After reading Swift 3 evolution on GCD, I am trying to create dispatch group. The problem is the group.notify(queue: do not notify when I pass DispatchQueue.main as a queue, although it does work for background queue.

Also I am not sure my syntax is all correct, as I am trying to convert code from Swift 2 to Swift 3.

typealias CallBack = (result: Bool) -> Void
func longCalculations (completion: CallBack) {

let backgroundQ = DispatchQueue.global(attributes: .qosBackground)

    let group = DispatchGroup()  
    var fill:[Int] = [] 
    for item in 0...200 {
        group.enter() 
        if item > 50 {
            fill.append(item)
        }
        group.leave() 
    }

//Below in the notify argument If I pass `backgroundQ`, it seems to work correctly but not when DispatchQueue.main is passed.

This code do not work

group.notify(queue: DispatchQueue.main, execute: {
    completion(result: true)
    })
 }

This works correctly

group.notify(queue: backgroundQ, execute: {
    completion(result: true)
    })
 }
_______________________________________________________

longCalculations() { print($0) }
like image 786
jyet Avatar asked Jul 24 '16 12:07

jyet


1 Answers

After reading post suggested by Matt, I found that I was submitting task to main queue and when I asked to be notified on main thread itself, it got in the deadlock.

I have altered the code and now it is working as intended,

typealias CallBack = (result: [Int]) -> Void
func longCalculations (completion: CallBack) {
  let backgroundQ = DispatchQueue.global(attributes: .qosDefault)
  let group = DispatchGroup()

  var fill:[Int] = []
  for number in 0..<100 {
      group.enter()
      backgroundQ.async(group: group,  execute: {  
          if number > 50 {
            fill.append(number)
          }
          group.leave()

          })
      }

     group.notify(queue: DispatchQueue.main, execute: {
       print("All Done"); completion(result: fill)
     }) 
}

longCalculations(){print($0)}
like image 70
jyet Avatar answered Oct 08 '22 18:10

jyet