在我的应用程序中运行ThreadSanitizer时,我在同时下载文件时出现了数据争用问题,如何解决
这是断点代码:
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten:
Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if let downloadUrl = downloadTask.originalRequest?.url?.absoluteString,
let download = activeDownloads[downloadUrl] {
//break point indicate here:-
download.progress = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite)
let totalSize = ByteCountFormatter.string(fromByteCount: totalBytesExpectedToWrite, countStyle: ByteCountFormatter.CountStyle.binary)
DispatchQueue.main.async(execute: {
if let trackIndex = self.trackIndexForDownloadTask(downloadTask), let trackCell = self.tableView.cellForRow(at: IndexPath(row: trackIndex, section: 0)) as? AmbientCell {
trackCell.progressView.progress = Double(download.progress)
if download.progress == 1.0 {
trackCell.progressView.isHidden = true
trackCell.downloadCompleted.isHidden = false
}
}
})
}
}
完整警告日志 - ThreadSanitizer: data race
答案 0 :(得分:1)
看起来你有一个从两个线程同时使用的下载管理器,并且你在两个线程中都设置了它的进度,这导致了错误。 首先,为什么?如果您要下载两个不同的文件,他们就不应该共享进度。如果它是同一个文件,是否应该同时下载? 在后一种情况下,您可能希望使用互斥锁保护共享下载管理器。请注意,即使在这种情况下,您仍然可以使用非单调值更新进度。