Question or problem in the Swift programming language:
I implement the following 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)") } } } }
And run as the following:
Run A:
gCDStudy = GCDStudy() gCDStudy.asyncSerial(1) gCDStudy.asyncSerial(2)
Run B
vgCDStudy2 = GCDStudy() gCDStudy2.asyncConcurrent(1) gCDStudy2.asyncConcurrent(2)
And the result 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
The result of 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
These results are the same, what is the different between these?
Sometimes these results are different.
Thanks
How to solve the problem:
Serial queues execute one task at a time in the order in which they are added to the queue whereas concurrent queues execute one or more tasks concurrently. An important thing to note is that, even for concurrent queues, tasks are started in the order in which they were added to the queue. Because of that, in your case, you'll probably see no change in the output as print
will be executed pretty fast by each thread in the concurrent queue so that it'll seem as if they were executed sequentially.
If you expect to see a difference, maybe you might try updating your code as follows:
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)") } } } }