I'm using Grand Central Dispatch to transforms elements of one array into another. I call dispatch_apply
on the source array, transform it into zero or more items, then add them to the destination array. This is a simplified example:
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)
I sometimes get an error on the append
line. The error is always one of:
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
I guess this is due to append
not being thread-safe. What did I do wrong and how to fix it?