gpt4 book ai didi

swift - DispatchGroup 和可能的竞争条件?

转载 作者:可可西里 更新时间:2023-11-01 00:40:56 34 4
gpt4 key购买 nike

以下是否会产生可能的竞争条件?

let syncGroup = DispatchGroup()
var tempData: [Int]
for index in 1...10 {
syncGroup.enter()
// Alamofire is being called in the following.
// I am leaving out implementation, just to simplify.
asyncTaskUsingAlamofire(completionHandler: { (data: [Data]) in
// Possible race condition?
// Should I use something like `sync()` and how?
tempData.append(data)
syncGroup.leave()
})
}
syncGroup.notify(queue: .main) {
// We can go on, all data is added to tempData
}

我可以看到 swift 有一个 sync() 如果你会如何解决这个问题?

最佳答案

串行队列

非常类似于Sulthan's answer ,我只是通常在这种情况下使用自定义串行队列

let group = DispatchGroup()
var results = [Int]()
let serialQueue = DispatchQueue(label: "serialQueue")

for _ in 1...10 {
group.enter()
asyncTaskUsingAlamofire { data in
serialQueue.async {
// Multiple instances of this block will be executed into a serial queue
// So max 1 block at a time
// This means results is accessed safely
results.append(contentsOf: data)
group.leave()
}
}
}

group.notify(queue: .main) {
print(results)
}

results 数组是安全访问的,因为 block 的每个实例都会改变它

results.append(contentsOf: data)
group.leave()

在串行队列中执行。

serialQueue.async {
results.append(contentsOf: data)
group.leave()
}

换句话说, block 的 10 个实例被排入 serialQueue一次执行一个

这确实保证了结果的安全访问。

关于swift - DispatchGroup 和可能的竞争条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43769838/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com