我在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
我觉得这是编译器中的一些错误,因为当我在发布模式下运行代码时它运行得很好。或者我在这里做错了什么?
阵列中有指针,绝对可以在你的脚下改变。它不是原始记忆。
数组不是线程安全的。数组是值类型,这意味着它们以线程安全的方式支持写入时复制(因此您可以自由地将数组传递给另一个线程,如果在那里复制,那就没问题),但是你不能在多个线程上改变相同的数组。 Array不是C缓冲区。它没有被允许有连续的记忆。它甚至没有承诺分配内存。数组可以在内部选择将“我当前都是零”存储为特殊状态,并为每个下标返回0。 (它没有,但它被允许。)
对于这个特定问题,您通常使用vDSP方法,如vDSP_vramp,但我知道这只是一个示例,并且可能没有解决问题的vDSP方法。但是,通常情况下,我仍然专注于Accelerate / SIMD方法,而不是调度到队列。
但是如果你要派遣到队列,你需要一个UnsafeMutableBuffer来控制内存(并确保内存甚至存在):
pixels.withUnsafeMutableBufferPointer { pixelsPtr in
DispatchQueue.concurrentPerform(iterations: threadCount) { thread in
for number in thread*size ..< (thread+1)*size {
let floating = Float(number)
pixelsPtr[number] = SIMD3(floating, floating, floating)
}
}
}
“不安全”表示现在是您的问题,以确保所有访问都是合法的,并且您没有创建竞争条件。
注意这里使用.concurrentPerform
。正如@ user3441734提醒我们的那样,一旦pixelsPtr
完成,.withUnsafeMutablePointer
不会被承诺有效。保证.concurrentPerform
在所有块完成之前不会返回,因此指针保证有效。
这也可以通过DispatchGroup完成,但.wait
需要在withUnsafeMutableBufferPointer
内部。