Swift’s multithreading technology is no different from Objective-C. Thread is the lightest of the three threads that normal programmers use. Each Thread object represents a Thread, but it needs to manage its life cycle and synchronization. Locking data for thread synchronization has some overhead.

Operation, GCD, Thread, Thread, Thread, Thread, Thread, Thread, Thread, Thread, Thread, Thread, Thread, Thread, Thread, Thread, Thread

If you’re serious, there’s another multithreading technique called pthread. We’ll talk a little bit about it at the end. But it is definitely not the multithreaded scheme that normal programmers need to use today. I don’t know if I’m gonna get sprayed to death.

1. There are three ways to establish a Thread

All of the code below is written using the old Swift 3.0.

Yes, you read that right. Old Swift 3.0. Swift 5.0 is on the way, and when I heard the news, I had mixed feelings. I was a little worried about Swift. Not long after 4.0 was released, 5.0 started. Hence the joke that learning iOS development requires proficiency in Swift1.0, Swift2.0, Swif 2.2… Four languages or something.

1.1 Use class method to create, run automatically

One with Selector, one without.

Thread.detachNewThread {
    print("A new thread,name:\(Thread.current)")} / / take a Selector that Thread. DetachNewThreadSelector (#selector(threadPrint), toTarget: self, with: nil)
Copy the code

Threads created this way will run automatically.

1.2 Practical construction method creation, need to run manually

There are two ways to create a Thread directly and run it.

Thread(block: <#T##() -> Void#>)
Thread(target: <#T##Any#>, selector: <#T##Selector#>, object: <#T##Any? # >)
Copy the code

Here is an example of a thread that needs to be manually started

   let customThread = Thread(target: self, selector: #selector(threadPrint), object: nil)
    customThread.start()
Copy the code

1.3 Extension method using NSObject

Anything that inherits from NSObject can easily be invoked in this way.

Let’s take a look at the source file:

extension NSObject { open func performSelector(onMainThread aSelector: Selector, with arg: Any? .waitUntilDone wait: Bool, modes array: [String]?) open func performSelector(onMainThread aSelector: Selector, with arg: Any? .waitUntilDone wait: Bool) @available(iOS 2.0, *) Open func Perform (_ aSelector: Selector, on THR: Thread, with arg: Any? .waitUntilDone wait: Bool, modes array: [String]?) @available(iOS 2.0, *) Open func Perform (_ aSelector: Selector, on THR: Thread, with arg: Any? .waitUntilDone wait: Bool) @available(iOS 2.0, *) Open Func Selector(inBackground aSelector: Selector, with arg: Any?)
}
Copy the code

2. Basic usage of Thread

The basic use of Thread is fairly simple, almost like GCD. There are also start, pause, cancel, block, set priority, and so on.

methods role
start Start the
cancel suspended
exit cancel
sleep blocking

Common properties of Thread

The name of the use
name Give the thread a name for easy lookup
stackSize Stack size, see how much space threads take up on the stack
isMainThread Is it the main thread
qualityOfService Quality of service, iOS8.0 launched in order to replace priority.
  • Note: Thread does not start immediately after setting start. It’s essentially a pool of schedulable threads waiting to be called by the CPU. Before the thread completes execution, the state may switch back and forth between the ready state and the running state. The state switch between the ready state and the running state is done by the CPU without programmer intervention.

  • Blocking: A running thread can block the execution of a thread by means of a sleep.

  • Exit: Thread exits automatically after completion of execution. If exit is executed, the thread forces exit. A few things to note:

    • Do not call it in the main thread, it will cause the UI thread to exit. I’ll see what you do when you quit!
    • After exit, all remaining code for the thread is not executed.
    • Before calling this method, be careful to release the objects created in C language, otherwise it will cause problems such as memory leakage.
  • Cancel: This cancel is the same as GCD, there is no real cancellation thread, just a flag. Cancellation requires its own implementation. That is, before the big man starts, determine the status of the flag bit. If you have never written the status judgment of this flag bit, then cancel is useless.

3. Use NSCondition to implement communication between threads

Remember the Semaphore in GCD? Multithreading: ADVANCED GCD, singleton, semaphore, task group. The NSCondition in Thread looks something like this.

There are only four ways to do this, so let’s take a look at them all:

Method names role
wait Makes the thread wait
wait(until limit: Date) -> Bool When the semaphore does not appear at a given time, it automatically continues
signal Wake up the thread
broadcast Wake up all waiting threads

NSCondition implements the NSLocking protocol, so it also has lock and unlock methods. Together, the thread synchronization problem can be solved by locking at the start of the thread and releasing the lock after the resource is acquired. To use it, place the code that needs to be locked between lock and unlock.

The main thing is not to put any mess into the lock code, which should be preempted to read and modify resources. Otherwise, one thread is executing while another thread is waiting, and multiple threads are doing that? !

Let’s do an example.

Requirements:

1. Download five pictures and five articles;

2. After downloading two pictures, pause the download and start the article download;

3. After downloading three articles, pause the download and continue downloading the remaining three images.

4. After downloading the pictures, download the remaining two articles.

Print print print print print print print print print

class ViewController: UIViewController {
    var downImages: Thread?
    var downArticles: Thread?
    
    let imageCondition = NSCondition()
    let articleCondition = NSCondition()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        downImages = Thread(target: self, selector: #selector(downloadImages), object: nil)
        downArticles = Thread(target: self, selector: #selector(downloadArticles), object: nil)downImages? .start() } @objc private functhreadPrint() {
        Thread.sleep(forTimeInterval: 2)
        print("After 2 seconds, I have been performed. I am \(Thread.current)")
    }
    
    @objc fileprivate func downloadImages() {
        for index in1... 5 {print("Downloading No.\(index) image.")
            Thread.sleep(forTimeInterval: 1)
            
            ifindex == 2 { //start downArticles. Start downArticles for downloading articles? .start() //Lock the image thread. Imagecondition.lock () imagecondition.wait () imagecondition.unlock ()}}print("All images have been completed."//Signaling the article when all images completed. // Activate articlecondition.signal ()} @objc fileprivate funcdownloadArticles() {
        for index in1... 5 {print("The No.\(index) article will be downloading.")
            Thread.sleep(forTimeInterval: 1)
            if index == 3 {
                //Signaling the image thread, let it continueImagecondition.signal () //Lock the article thread. Articlecondition.lock () articlecondition.wait () articlecondition.unlock ()}}print("There are 5 articles.")}}Copy the code

Let’s print the final print:

All right. One last word about pThread, which is largely unused.

4. pthread

I don’t know who’s using this multi-threaded technique anymore, except for the occasional interview. Pthread is short for POSIX thread. Represents a cross-platform threading interface.

The atypical geek wanders through Google for a long time to be able to write a Demo, then, then, then gives up…

How can you be so stubborn, in the OC era it was still possible to write and create. So I went to the Apple Manual, and, and, and gave up…

Threading Programming Guide. POSIX Thread Man Page However, apparently the link was removed.

Apple Dad… I really want to hammer your small chest. All right, give up.

Finally, all the code is here: download it from gitHub and give it a Star ~(~ o ~ 3 ~) ~ love you