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

Ios Swift:串行队列中的线程安全计数器,ios,multithreading,swift,atomic,Ios,Multithreading,Swift,Atomic,我正在处理异步排队进程,我需要更新一个计数器来跟踪进度 这是一个接近我的代码的示例(我没有发布我的实际代码,因为它与特定库的回调一起工作,这不是重点): 用文字来说,这段代码基本上只需从网络下载内容,并将其添加到数组中。只有在下载了所有数据后,才会调用代码dispatch\u group\u notify()的最后一部分 有趣的是,myData.count==url.count返回true,这意味着执行闭包,但计数器总是0。我的猜测是,[]是线程安全的,而Int不是 我如何解决这个问题?我已经试

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

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

用文字来说,这段代码基本上只需从网络下载内容,并将其添加到数组中。只有在下载了所有数据后,才会调用代码
dispatch\u group\u notify()
的最后一部分

有趣的是,
myData.count==url.count
返回true,这意味着执行闭包,但
计数器总是
0
。我的猜测是,
[]
是线程安全的,而
Int
不是


我如何解决这个问题?我已经试过了,但没用

为什么不使用NSLock来阻止多个线程尝试访问您的“关键部分”。您甚至可以通过以下方式摆脱dispatch group:

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)
    }
}
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)
    }
}