Process Array in parallel using GCD

前端 未结 5 1329
青春惊慌失措
青春惊慌失措 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 12:00

    I think Nate is right: there are race conditions with the summary variable. To fix it, I used summary's memory directly:

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

    This works (so far).

    EDIT Mike S has a very good point, in his comment below. I have also found this blog post, which sheds some light on the problem.

提交回复
热议问题