swift – 并行添加数组
发布时间:2020-12-14 02:23:49 所属栏目:百科 来源:网络整理
导读:我正在使用Grand Central Dispatch将一个数组的元素转换为另一个数组.我在源数组上调用dispatch_apply,将其转换为零个或多个项,然后将它们添加到目标数组.这是一个简化的例子: let src = Array(0..1000)var dst = [UInt32]()let queue = dispatch_queue_cre
我正在使用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) 我有时会在追加行上出错.错误总是以下之一: 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 我想这是因为追加不是线程安全的.我做错了什么以及如何解决?
正如您所发现的,Swift可能会重新定位阵列以提高内存效率.当你运行多个追加时,它必然会发生.我的猜测是,与转换相比,附加到阵列的成本非常低.您可以创建一个串行队列来扩展dst数组:
let src = Array(0..<1000) var dst = [UInt32]() let queue = dispatch_queue_create("myqueue",DISPATCH_QUEUE_CONCURRENT) let serialQueue = dispatch_queue_create("mySerialQueue",DISPATCH_QUEUE_SERIAL) let serialGroup = dispatch_group_create() dispatch_apply(src.count,queue) { i in let result = arc4random_uniform(UInt32(i)) // Your long-running transformation here dispatch_group_async(serialGroup,serialQueue) { dst.append(result) } } // Wait until all append operations are complete dispatch_group_wait(serialGroup,DISPATCH_TIME_FOREVER) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |