SWIFT 5.9
我正在try 同时对数组的一些非重叠子范围进行排序.到目前为止,我的方法看起来像这样:
// Not the real array setup, but sufficiently representative
let arraySize = 1_000_000
var someArray = [Int]()
someArray.reserveCapacity(arraySize)
for _ in 0..<arraySize {
someArray.append(.random(in: 0...1_000_000))
}
// Let's say we want to break the array into 6 SubSequences of
// roughly equal size and sort each one
let divisions = 6
var divisionLength = arraySize / divisions
// Guarantee that the last division will be at least as large
// as the remainder of the array
if arraySize % divisions != 0 { divisionLength += 1 }
await withTaskGroup(of: Void.self) { taskGroup in
var currentIndex = 0
while currentIndex < someArray.endIndex {
let sliceStart = currentIndex
let sliceEnd = min(currentIndex + divisionLength, someArray.endIndex)
currentIndex = sliceEnd
taskGroup.addTask {
// compilation error: mutation of captured var 'someArray'
// in concurrently-executing code
someArray[sliceStart..<sliceEnd].sort()
}
}
await taskGroup.waitForAll()
}
我有一个潜在的怀疑,由于Swift处理可变值类型的方式,不存在一种机制来说"Trust Me Bro™"关于并发可变性.
这是基于我的理解,即使我将排序函数&;mutex抽象为它操作的范围,CoW也会使其他线程持有的引用无效.
尽管如此,我还是想确切地知道--是否存在某种并发安全覆盖来允许我这样做?或者,有没有完全不同的方法?