Multithreading-1 basic usage

Basic usage

The most common purpose of multithreading is

1. Put time-consuming calculation operations on the child thread

2. Notify the main thread to render the UI

The only difference is that it is a serial queue and a parallel queue. For example, webImage is parallel. When it comes, it will notify the child thread to process and then call a different imageView to display it. For example, database operations are still serial, at least Locked to ensure safe reading

for i in 2...6000 {    DispatchQueue.global().async {        print(i)        DispatchQueue.main.async {           print(i,"main")        }    }}

The above usage is the basic usage, first the child thread, and then set a main thread to render the UI magic horse

DispatchWorkItem

This seems to come with Swift, OC has never seen this thing

DispatchWorkItem itself is a class, and there are two initialization methods

And this block is actually a () -> Void, and Void is an alias of (), so it is a closure with no parameters and no return value, and when there is only one closure in the function

let item = DispatchWorkItem        {            print("123",Thread.current)        }

It can be written as above in the way of trailing closure

      let item = DispatchWorkItem        {            print("123",Thread.current)        }        let mainItem = DispatchWorkItem        {            print("main",Thread.current) //main <NSThread: 0x600001e4c580>{number = 1, name = main}         }        DispatchQueue.global().async(execute: item)        DispatchQueue.main.async(execute: mainItem)

This is no different from ordinary GCD usage, but it is convenient to encapsulate. Relatively speaking, Swift recommends this method.

Delayed execution

DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + 0.5, execute: item)

For example, this code is executed with a delay of 0.5s

Once

fileprivate var INITTASK:Void ={    let id = "123456"    //初始化操作}()

The content in this bracket will only be executed once, and the function stack will be printed out

In fact, the essence is dispatch_once