我实现了以下类:
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
这些结果是一样的,这些结果有什么不同?
有时这些结果是不同的。
由于
答案 0 :(得分: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)")
}
}
}
}