Wednesday, May 8, 2019

Understanding iOS Dispatch queue and GCD (Grand Centre Dispatch)

Concurrency Mode:
There are two types of dispatch queue in term of concurrency: concurrent queue and serial queue.

For serial queue, the next task gets started only if the previous task is finished, so the tasks are executed sequentially. There should only be one thread for each serial queue, as the next task will not start before the previous task returns.

For concurrent queue, the previous task always starts before the next task, but the next task(s) can start before the previous task returns. As multi tasks run in parallel, so a concurrent queue can create and use multiple threads to executes its tasks.


Queue Creation:
There are three types of dispatch queue in term of queue creation: Main, Global, and custom.

The Main dispatch queue is a globally available serial queue that executes tasks on the application’s main thread, it is only for UI activities, the qos class for main queue is
Dispath.DispatchQoS.QoSClass.userInteractive
The below code can be used to get main queue object
let mainQueue = DispatchQueue.main


The Global dispatch queue are system dispatch concurrent queues, QosClass parameter can be used to specify the priority of the queue.
The below code can be used to get the global queue object

let globalQueue = DispatchQueue.global(qos: .default)


Custom dispatch queue can be created by developers, it can either be serial queue or concurrent queue depending on attribute parameter
//create serial queue
let customSerialQueue = DispatchQueue(label: "my.custom.serial")
//create concurrent queue
let customConcurrentQueue = DispatchQueue(label: "my.custom.concurrent", qos:.default, attributes: .concurrent)


Dispatch task
Sync task
Synced task will block the current caller's thread, until the task returns, so it can have a return value to the caller. 
Note if the current task is running in main or a serial queue, then it cannot invoke another synced task to the same queue, otherwise, the app will crash due to a dead lock. However, it is fine to dispatch a sync task to the same queue if the queue is a concurrent queue (global or custom concurrent queue).

From main thread to execute a sync task on a global or custom queue, will cause the code to be run in the main thread instead of the background thread.

Async task
Asynced task is more common in application implementation. Since the task runs asynchronously so it cannot return any result to the caller.
Note, as mobile device usually only has limited cores for background thread to use, so application should avoid create two many async tasks which blocks for some reason, as once a queue creates 64 threads, the application will hangs. In addition, creating too many threads in CPU intensive operation will only increase the context switch,  and deteriorate the app performance.  
      

No comments:

Post a Comment