我正在处理异步排队进程,我需要更新计数器以跟踪进度。
这是一个接近我的代码的示例(我没有发布我的实际代码,因为它适用于特定库的回调,并不是真的重点):
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
不是。{1}}。
答案 0 :(得分:0)
为什么不使用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)
}
}