如何同时更新数组?

时间:2018-02-14 05:07:14

标签: ios arrays swift concurrency nsoperationqueue

我试图意识到这一点: 我有四个数组和一个“calculateResult”函数来改变它们。这些数组的元素数量为2 ^ n,其中n是用户定义的值。该函数在循环中调用(在实际项目中,迭代次数可以是2 ^ 10,例如)。 然后将数组分成几部分(在实际项目中的零件数=处理器数)和这部分并行范围内的“calculateResult”。

我需要的具体情况(数组计数= 2 ^ 10 = 1024,部件数= 4):

import Foundation

    func calculateResult(inRange calculationRange: CountableClosedRange<Int>) -> (ArraySlice<Double>, ArraySlice<Double>, ArraySlice<Double>, ArraySlice<Double>) {
        var array1 = Array(repeating: 0.0, count: calculationRange.count)
        var array2 = Array(repeating: 0.0, count: calculationRange.count)
        var array3 = Array(repeating: 0.0, count: calculationRange.count)
        var array4 = Array(repeating: 0.0, count: calculationRange.count)

        var iRes = 0
        for i in calculationRange {
            array1[iRes] = Double(i * 1)
            array2[iRes] = Double(i * 10)
            array3[iRes] = Double(i * 100)
            array4[iRes] = Double(i * 1000)

            iRes += 1
        }

        return (ArraySlice(array1), ArraySlice(array2), ArraySlice(array3), ArraySlice(array4))
    }

    var result1 = Array(repeating: 0.0, count: 1024)
    var result2 = Array(repeating: 0.0, count: 1024)
    var result3 = Array(repeating: 0.0, count: 1024)
    var result4 = Array(repeating: 0.0, count: 1024)

    func calculateResConcurrent() {
        let operationQueue = OperationQueue.init()

        let op1 = BlockOperation.init {
            print("Operation \(0)...")
            (result1[0...255], result2[0...255], result3[0...255], result4[0...255]) = calculateResult(inRange: 0...255)
            print("Operation \(0) DONE")
        }
        let op2 = BlockOperation.init {
            print("Operation \(1)...")
            (result1[256...511], result2[256...511], result3[256...511], result4[256...511]) = calculateResult(inRange: 256...511)
            print("Operation \(1) DONE")
        }
        let op3 = BlockOperation.init {
            print("Operation \(2)...")
            (result1[512...767], result2[512...767], result3[512...767], result4[512...767]) = calculateResult(inRange: 512...767)
            print("Operation \(2) DONE")
        }
        let op4 = BlockOperation.init {
            print("Operation \(3)...")
            (result1[768...1023], result2[768...1023], result3[768...1023], result4[768...1023]) = calculateResult(inRange: 768...1023)
            print("Operation \(3) DONE")
        }

        operationQueue.addOperations([op1, op2, op3, op4], waitUntilFinished: true)
    }

    let numberOfIterations = 200
    for i in 0...numberOfIterations {
        print("\nMain iteration \(i) of \(numberOfIterations)")
        calculateResConcurrent()
    }

    print("")
    print(result1.last!, result2.last!, result3.last!, result4.last!) //Correct result is: (1023.0, 10230.0, 102300.0, 1023000.0)

我运行它,有时会崩溃并出现错误:“致命错误:UnsafeMutablePointer.deinitialize with negative count”或返回错误的结果。 帮助我找到错误并意识到这一点,请:-)我是一个快速的新人。

1 个答案:

答案 0 :(得分:0)

你最终可以做的是引入一个DispatchQueue同步写入数组,并通过BlockOperation继续同时运行其余的逻辑,所以你的函数可能是:

let queue = DispatchQueue(label: "syncQueue")

func calculateResConcurrent() {
    let operationQueue = OperationQueue.init()
    operationQueue.maxConcurrentOperationCount = 4
    let ops:[BlockOperation] = [0...255, 256...511, 512...767, 768...1023].map { range in
        let op = BlockOperation.init(block: {
            let res = calculateResult(inRange: range) // concurrent
            queue.sync(execute: { // synchronous
                result1.replaceSubrange(range, with: res.0)
                result2.replaceSubrange(range, with: res.1)
                result3.replaceSubrange(range, with: res.2)
                result4.replaceSubrange(range, with: res.3)
            })
            print("Operation \(range) finished")
        })
        return op
    }
    operationQueue.addOperations(ops, waitUntilFinished: true)
}