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

标签 ios multithreading swift atomic

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

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

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/

相关文章:

ios - Objective-C block 。上下文捕获相同的变量/复制相同的 NSStackBlock

ios - 区分 LLDB 中的 iOS 模拟器和设备

ios - UITableView insertRowsAtIndexPaths :WithRowAnimation without freeze UI

c++ - 多线程的 shared_ptr 销毁是否安全?

swift - 在 Storyboard或代码中禁用 UITableViewController 中静态 TableView 的单元格选择的最简单方法是什么

iOS 如何使 inputaccessoryview 中的 TextView 成为第一响应者?

使用蓝牙控制 iOS AVPlayer

java - 始终使用 'this' 作为监视器锁是可以接受的吗?

ios - 如何使用 Swift 创建具有动态单元格高度的静态单元格

ios - 尝试将 Linkedin SDK 集成到我的 Swift 项目时出错