Process Array in parallel using GCD

前端 未结 5 1322
青春惊慌失措
青春惊慌失措 2020-12-09 11:22

I have a large array that I would like to process by handing slices of it to a few asynchronous tasks. As a proof of concept, I have the written the following code:

5条回答
  •  一向
    一向 (楼主)
    2020-12-09 11:46

    When you use the += operator, the LHS is an inout parameter -- I think you're getting race conditions when, as you mention in your update, Swift moves around the array for optimization. I was able to get it to work by summing the chunk in a local variable, then simply assigning to the right index in summary:

    func calcSummary() {
        let group =  dispatch_group_create()
        let queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)
    
        for i in 0 ..< 10 {
            dispatch_group_async(group, queue, {
                let base = i * 50000
                var sum = 0
                for x in base ..< base + 50000 {
                    sum += self.array[x]
                }
                self.summary[i] = sum
            })
        }
    
        dispatch_group_notify(group, queue, {
            println(self.summary)
        })
    }
    

提交回复
热议问题