multithreading

Synchronous, asynchronous, and serial, parallel/concurrent

Before we start, let’s review the differences between these four!

  • Synchronization: In the case of multiple tasks, you can execute task B only after task A is complete. There is only one thread.

  • Asynchronous: In the case of multiple tasks, one task A is being executed and the other task B can be executed at the same time. Task B does not wait for task A to finish. Multiple threads exist.

    Parallelism and concurrency are two forms of asynchrony

  • Parallelism: Parallelism is the real asynchrony. Multi-core CUP can open multiple threads for simultaneous execution of multiple tasks without interfering with each other. As shown in the figure above, parallelism is actually the same as asynchronous legend.

  • Concurrency: pseudo-asynchrony. You can only have one thread in a single-core CPU, but you want to perform multiple tasks. At this point, only one thread can constantly switch tasks, let the user think that they are executing at the same time

Processes and threads

Process: A running application

Threads: A process (application) has at least one thread in which all tasks of the process are executed

Serial of threads

  • The execution of tasks in a thread is sequential

  • If multiple tasks are executed in a thread, they can only be executed sequentially

The difference between threads and processes

  1. Threads are CPU calls (the smallest unit to perform a task)
  2. A process is the unit of CPU allocation and scheduling (CPU does not allocate resources to threads).
  3. A program can correspond to multiple processes, a process can have multiple threads, but there is at least one thread
  4. Threads within the same process share the resources of the process

Processes can be likened to a factory, and processes are the workers in that factory

multithreading

As mentioned above, there should be at least one thread in a process. If there are multiple threads, each thread can perform different tasks in parallel (at the same time), which can improve the execution efficiency of the program

  • The execution of tasks within a thread is sequential
  • The execution of tasks can be parallel between threads

The principle of

  • In fact, the CPU can only process one thread at a time
  • The above mentioned that each thread can perform different tasks at the same time, in fact, the CPU is fast scheduling between multiple threads, and this process is very fast, thus creating the illusion of multi-thread parallelism (note the difference between parallel and concurrent).
  • So, in fact, true multithreading is concurrent

Consider: What happens if there are too many threads?

  • The CPU also consumes resources when scheduling threads, and if there are too many threads, the CPU consumes a lot of resources
  • Each thread is scheduled to execute less often (thread execution efficiency is reduced)

Advantages and disadvantages of multi-threading

Advantages:

  • Can improve the execution efficiency of the program
  • Appropriately improve resource utilization (CPU, memory utilization)

Disadvantages:

  • Creating a thread requires overhead
  • If a large number of threads are opened, the performance of the program will be reduced
  • The more threads, the more overhead the CPU has in scheduling threads
  • Programming is more complex: communication between threads, data sharing between multiple threads

The main thread

When an iOS application runs, it starts a thread by default, called the “main thread” or “UI thread”

The main role

  • The UI is displayed or refreshed
  • Handle UI events (click, scroll, etc.)

Note: Any UI-related events must be implemented in the main thread

Pay attention to the point

  • Do not place time-consuming operations on the main thread. If you do, the interface will lag

    • Because the execution inside the thread is serial
  • Put time-consuming operations on child threads.

The thread

  1. Get the main thread
NSThread *mainThread = [NSThread mainThread];
Copy the code
  1. Get the current process
NSThread *currentThread = [NSThread currentThread];
Copy the code
  1. Judge the main thread
    1. Print thread, if its number=1, that is the main thread
BOOL isMainThreadA = [NSThread isMainThread]; NSThread *currentThread = [NSThread currentThread]; BOOL isMainThreadA = [currentThread isMainThread];Copy the code

IOS multithreading implementation scheme

Create and start a thread

An NSThread object represents a thread

  1. Methods a

Threads need to be created and startedYou can also set the thread name and thread priority

  1. Method 2

Three (3) methodThe latter two methods are quick and easy to create a thread, but only method one can get the thread object

NSThread Indicates the life cycle of a thread

You may be wondering: how do you get the thread object in other parts of the program when the local variables in a thread-creating function are released as soon as the function goes to its own}?

Consider the life cycle of nsThreads

When the task completes, the thread is released

(Be sure to understand the thread lifecycle!)

Thread state

Ready, executed, blocked, dead

  • Blocked: The thread is still in memory, but not in the schedulable thread pool
  • Death: a thread is moved from a schedulable thread to memory and then released from memory (so you cannot restart a thread after it has died using the start method because it is no longer in memory).

Multithreading security risks

  1. Resource sharing
  • A resource may be shared by multiple threads, which means that multiple threads may access the same resource
  • For example, multiple threads accessing the same object, the same file…

Then it is easy to cause data confusion and data security problems

This is a typical example

Solution – Mutex

  • Mutex must be globally unique
  • Mutex can effectively prevent data security problems caused by multi-thread resource grabbing
  • It consumes a lot of CPU resources
  • Causes thread synchronization

Atomic and nonatomic

  • Nonatomic: Non-atomic property that does not lock setters
    • Non-thread-safe
    • Suitable for mobile devices with small memory
  • Atomic: Atomic property that locks setter methods
    • Thread safety
    • Consume resources

Nonatomic is used in general development cases

Communication between threads

  • The data transfer
  • Task transfer