Ios 什么';调度队列并发和调度队列串行之间的区别是什么
我实现了以下类:Ios 什么';调度队列并发和调度队列串行之间的区别是什么,ios,swift,grand-central-dispatch,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){
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)")
}
}
}
}
跑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
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)")
}
}
}
}
类GCD研究{
func异步串行(时间:双精度){
让queue=dispatch\u queue\u create(“dispatch\u queue\u SERIAL”,dispatch\u queue\u SERIAL)
对于0中的i..在每个示例中,您只向队列分配一个块。若要查看差异,请向每个队列分配多个块。换句话说,将对dispatch\u async
的调用放入循环中。
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
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)")
}
}
}
}