gpt4 book ai didi

ios - Swift:串行队列中的线程安全计数器

转载 作者:行者123 更新时间:2023-11-30 14:15:46 24 4
gpt4 key购买 nike

我正在处理异步排队进程,我需要更新计数器来跟踪进度。

这是一个接近我的代码的示例(我没有发布我的实际代码,因为它适用于特定库的回调,但这不是重点):

var downloadGroup = dispatch_group_create()

counter = Float(0)
total = Float(urls.count)

var myData = [MyData]()

for url in urls {
dispatch_group_enter()
process.doAsync(url) {
// Success callback called on main thread

data in

myData.append(data) // Append data from url to an array

counter++ // Here counter should increment for each completed task, but it doesn't update
progressCallback(completedPercentage: counter/total)
dispatch_group_leave(downloadGroup)
}
}

dispatch_group_notify(downloadGroup, dispatch_get_main_queue()) {
if myData.count == urls.count {
println("All data retrieved")
}
}

用文字表达这段代码,它基本上只是从网络下载东西,并将其添加到数组中。只有当所有数据都下载完毕后,最后部分代码dispatch_group_notify()被调用。

有趣的是myData.count == urls.count返回true,表示闭包执行完毕,但是counter总是0 。我的疯狂猜测是[]是线程安全的,而 Int不是。

如何解决这个问题?我已经尝试过thisthis但它不起作用。

最佳答案

为什么不使用 NSLock 来防止多个线程尝试访问您的“关键部分”。您甚至可以摆脱调度组,这样做:

let lock = NSLock()
counter = 0 // Why was this a float shouldn't it be an Int?
total = urls.count // This one too?

var myData = [MyData]()

for url in urls {
dispatch_group_enter()
process.doAsync(url) { data in
// Since this code is on the main queue, fetch another queue cause we are using the lock.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
lock.lock()
myData.append(data) // Append data from url to an array
++counter
// Check inside the critical section only.
if myData.count == urls.count {
println("All data retrieved")
// Do your stuff here get the main queue if required by using dispatch_async(dispatch_get_main_queue(), { })
}
lock.unlock()
})
// Do the rest on the main queue.
progressCallback(completedPercentage: counter/total)
}
}

关于ios - Swift:串行队列中的线程安全计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31211720/

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