Swift中concurrentPerform引发Double Free Error问题排查求助
稀疏矩阵与向量并行相乘在
-Ofast优化下出现Double Free Error问题 我编写了一段稀疏矩阵与向量相乘的并行代码,通过存储每行非零元素数量及该行首个元素在数组中的起始索引,确保输出向量的每个元素不会被多线程同时写入。这段代码在无优化构建或Debug模式下运行正常,但将优化级别设置为-Ofast时,出现了Double Free Error。
func parallelVectorMultiply(vector: Vector<T>) -> Vector<T> { guard space == vector.space else { fatalError("Number of columns in the matrix must match the size of the vector.") } var outputElements = [T](repeating: T(0), count: space.dimension) DispatchQueue.concurrentPerform(iterations: space.dimension) { row in let start_idx = row_first_element_offsets[row] if start_idx == -1 { return } let end_idx = start_idx + nonzero_elements_per_row[row] var rowSum = T(0) for i in start_idx..<end_idx { rowSum = rowSum + values[i].value * vector[values[i].col] } outputElements[row] = rowSum } return Vector(elements: outputElements, in: space) }
我预期不会出现错误,矩阵A与向量X相乘的公式为:
$$AX = Y$$
其中:
$$Y_i = \sum_k A_{ik} X_k$$
代码中先计算该行的求和结果,再将其存入输出数组对应的元素中,理论上不会有两个线程同时操作数组的同一个元素,请问可能遗漏了什么?
内容的提问来源于stack exchange,提问作者George Tait
相关产品推荐
相关产品推荐

