我偶然发现了 Swift 5 中的并发和数组问题。为了重现该问题,我将代码简化为以下片段:
import Dispatch
let group = DispatchGroup()
let queue = DispatchQueue(
label: "Concurrent threads",
qos: .userInitiated,
attributes: .concurrent
)
let threadCount = 4
let size = 1_000
var pixels = [SIMD3<Float>](
repeating: .init(repeating: 0),
count: threadCount*size
)
for thread in 0..<threadCount {
queue.async(group: group) {
for number in thread*size ..< (thread+1)*size {
let floating = Float(number)
pixels[number] = SIMD3<Float>(floating, floating, floating)
}
}
}
print("waiting")
group.wait()
print("Finished")
当我使用 Xcode 版本 10.2 beta 4 (10P107d) 在调试模式下执行此操作时,它总是崩溃并出现如下错误:
Multithread(15095,0x700008d63000) malloc: *** error for object 0x104812200: pointer being freed was not allocated
Multithread(15095,0x700008d63000) malloc: *** set a breakpoint in malloc_error_break to debug
我觉得这是编译器中的一些错误,因为当我在发布模式下运行代码时,它运行得很好。还是我在这里做错了什么?