微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift – 并行添加数组

我正在使用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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐