我使用Grand Central Dispatch將一個數組的元素轉換爲另一個數組。我在源數組上調用dispatch_apply
,將其轉換爲零個或多個項目,然後將它們添加到目標數組中。這是一個簡單的例子:並行添加到數組
let src = Array(0..<1000)
var dst = [UInt32]()
let queue = dispatch_queue_create("myqueue", DISPATCH_QUEUE_CONCURRENT)
dispatch_apply(src.count, queue) { i in
dst.append(arc4random_uniform(UInt32(i))) // <-- potential error here
}
print(dst)
我有時坐上append
線的錯誤。該錯誤是始終之一:
1. malloc: *** error for object 0x107508f00: pointer being freed was not allocated
2. fatal error: UnsafeMutablePointer.destroy with negative count
3. fatal error: Can't form Range with end < start
我想這是由於append
不是線程安全的。我做錯了什麼以及如何解決?
比較http://stackoverflow.com/questions/26693838/process-array-in-parallel-using-gcd。 –
感謝@MartinR。這個問題改變了數組的現有值,而不是追加到它。 'withUnsafeMutablePointer'沒有'append'方法 – Jenny
正如你已經注意到的,append()不是線程安全的。您可能必須先創建必要大小的數組。然後你可以使用引用的Q&A中的方法從多個線程並行地填充數組。 –