When we use network requesting, always use escaping closure to complete the data passed from net to our UI, though that generally works, but when getting into some intricate cases, we need to use nested clousure, which is not elegant, so study Threading Control Tech is useful for us to code better.

For example, we need to request a Image from internet, we can request data in the background, and allow UI moves quickly in the main thread, after fetched data, refresh the Image Control in main thread.

What Is GCD

From Swift3 we really step into the world of Multi Threading Coding, where we have elegant grammer unlike the infrastructure developing with C in the past, Apple provided brand new grammer for us. However that is 3 or 4 years ago, now we just use several lines we can complete our tasks.

GCD is the logogram of Grand Central Dispatch, the main part of it is Dispatch Queue. Queue can be regard as a assembly line in a factory. If we adding tasks to one queue (or main queue), that calls one thread, if we created 2 or more queue, and allocate tasks to them, that calls multi thread.

Sync Async

At First, I have to introduce a concept calls Dispatch Queue, which is called as Queue before, first we should import Foundation, and initialize a queue waiting for task.

let queue = DispatchQueue(label: "zrzz.site")

The basic method of initialize DispatchQueue has one parameter, label is decided by you, as long as it is unique.

Sync and Async, the logogram of Synchronizeand Asynchronize, as its literal meaning, we can make our queue run two tasks synchronously or asynchronously. To realize it better, plz run codes below and observe results.

![image-20200902105351441](/Users/zrzz/Library/Application Support/typora-user-images/image-20200902105351441.png)

We create one thread, let it syncly run a for loop, and let main thread (in the out side) use sync method, and Cpu exec our tasks by order.

What if we use async method? Let’s check.

![image-20200902105530265](/Users/zrzz/Library/Application Support/typora-user-images/image-20200902105530265.png)

As expected, two tasks run asyncly, that is multi thread.

Quality of Service (QoS)

文章作者: X Mεl0n
文章链接: http://www.zrzz.site/2020/08/31/Swift-GCD/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 X Mεl0n | 随手记