DISPATCH_QUEUE_CONCURRENT和DISPATCH_QUEUE_SERIAL有什么区别?

9
我实现了以下类:

class:

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

运行B的结果:

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

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

有时候这些结果是不同的。

谢谢


1
每个示例中您只向队列分派一个块。为了看到区别,请向每个队列分派多个块。换句话说,将对dispatch_async的调用放在循环内部。 - rmaddy
1个回答

11

串行队列按照添加到队列中的顺序逐个执行任务,而并发队列可以同时执行一个或多个任务。需要注意的一点是,即使对于并发队列,任务也是按照添加到队列中的顺序启动的。因此,在您的情况下,由于每个线程在并发队列中非常快地执行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)")
      }
    }
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接