ios - DISPATCH_QUEUE_CONCURRENT 和 DISPATCH_QUEUE_SERIAL 有什么区别

标签 ios swift grand-central-dispatch

我实现了以下类:

class GCDStudy {

    func asyncSerial(time:Double){
        let queue = dispatch_queue_create("DISPATCH_QUEUE_SERIAL",DISPATCH_QUEUE_SERIAL)

        dispatch_async(queue){

            var i:Double = 0
            while(i < 3){
                i++
                print("asyncSerial -wait:\(time)-\(i)")

            }
        }

    }

    func asyncConcurrent(time:Double){

        let queue = dispatch_queue_create("DISPATCH_QUEUE_CONCURRENT",DISPATCH_QUEUE_CONCURRENT)

        dispatch_async(queue){
            var i:Double = 0
            while(i < 3){
                i++
                print("asyncConcurrent -wait:\(time)-\(i)")
            }
        }
    }
}

然后运行如下:

运行 A:

gCDStudy = GCDStudy()
gCDStudy.asyncSerial(1)
gCDStudy.asyncSerial(2)

运行 B

vgCDStudy2 = GCDStudy()
gCDStudy2.asyncConcurrent(1)
gCDStudy2.asyncConcurrent(2)

结果 RunA:

asyncSerial -wait:1.0-1.0
asyncSerial -wait:2.0-1.0
asyncSerial -wait:1.0-2.0
asyncSerial -wait:2.0-2.0
asyncSerial -wait:1.0-3.0
asyncSerial -wait:2.0-3.0

RunB的结果:

asyncSerial -wait:1.0-1.0
asyncSerial -wait:2.0-1.0
asyncSerial -wait:1.0-2.0
asyncSerial -wait:2.0-2.0
asyncSerial -wait:1.0-3.0
asyncSerial -wait:2.0-3.0

这些结果是一样的,它们之间有什么不同?

有时这些结果是不同的。

谢谢

最佳答案

串行队列按照它们被添加到队列的顺序一次执行一个任务,而并发队列同时执行一个或多个任务。需要注意的重要一点是,即使对于并发队列,任务也是按照它们被添加到队列中的顺序启动的。因此,在您的情况下,您可能看不到输出有任何变化,因为 print 将由并发队列中的每个线程快速执行,因此看起来好像它们已执行顺序。

如果您希望看到差异,也许您可​​以尝试按如下方式更新您的代码:

class GCDStudy {

  func asyncSerial(time: Double) {
    let queue = dispatch_queue_create("DISPATCH_QUEUE_SERIAL", DISPATCH_QUEUE_SERIAL)

    for i in 0..<3 {
      dispatch_async(queue) {
        print("asyncSerial -wait:\(time)-\(i)")
      }
    }
  }

  func asyncConcurrent(time: Double) {
    let queue = dispatch_queue_create("DISPATCH_QUEUE_CONCURRENT", DISPATCH_QUEUE_CONCURRENT)

    for i in 0..<3 {
      dispatch_async(queue) {
        print("asyncConcurrent -wait:\(time)-\(i)")
      }
    }
  }
}

关于ios - DISPATCH_QUEUE_CONCURRENT 和 DISPATCH_QUEUE_SERIAL 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33622876/

相关文章:

ios - 在 FSCalendar 中设置下一个上一个按钮

ios - 在 MPNowPlayingInfoCenter 中设置值无效

parallel-processing - 大量线程消耗对 ARM(4 核 A72)与 x86(2 核 i5)的影响

ios - dispatch_get_current_queue() 已弃用,是否有安全 CoreData 的替代方案?

ios - Swift 在同一个 UICollectionView 中有不止一种行为

ios - 我应该如何在 iOS 中使用 GCD dispatch_barrier_async(似乎在其他 block 之前而不是之后执行)

iphone - NSAttributedString 能否用于将 native 应用程序操作与文字联系起来?

ios - 无法在 iOS 6 中保存 EKReminder

ios - Swift...在运行时更改 .js 文件的变量

ios - 强制使用参数名称,但只是其中的一部分