In this section, we mainly understand some theoretical knowledge of multithreading.

Processes and threads

define

process
  • A process is an application that is running in the system.
  • Each process is independent of the other, and each process runs in its own dedicated and protected memory space.
  • The Activity Monitor allows you to view processes that are running on the Mac system.
thread
  • A thread is the basic execution unit of a process, in which all tasks of a process are executed.
  • In order for a process to perform a task, it must have threads, at least one thread.
  • By default, the program starts a thread, which is called the main thread or UI thread.

Relationship between

  • Address space: Threads of the same process share the address space of the same process, while processes are independent of each other.
  • Resource ownership: Threads in the same process share the resources of the same process, such as memory, I/O, and CPU, but resources between processes are independent.

supplement

  1. The crash of one process in protected mode does not affect other processes, but the crash of one thread kills the entire process. So multi-processing is more robust than multi-threading.
  2. Process switchover consumes large resources and is efficient. So when it comes to frequent switching, threads are better than progressions. Also, if you require concurrent operations that share variables at the same time, use threads instead of processes
  3. Execution process: Each independent process has a program run entry, sequential execution sequence, and program entry. However, threads cannot execute independently and must depend on the application, which provides multiple thread execution control.
  4. Threads are the basic unit of processor scheduling, but processes are not.
  5. Threads have no address space and are contained in the process address space.

Principle of multithreading

  • forA single core CPU.The CPU can only process one thread at a timeThat is, only one thread is working,
  • In the iOSMultithreading simultaneous executionIs the essence of the CPU in multiple tasks directly to quickly switch, due to the CPU scheduling thread time is fast enough, resulting in the effect of multi-threading “simultaneous” execution. Where the switching interval isTime slice.

Advantages of multithreading

  • Can improve the execution efficiency of the program
  • Increase resource utilization (CPU, memory)
  • The task on the thread is automatically destroyed after it completes execution

Disadvantages of multithreading

  • Starting threads requires a certain amount of memory (by default, each thread takes up 512 KB and 90ms of time).
  • If a large number of threads are enabled, a large amount of memory space will be occupied and the performance of the program will be reduced.
  • The more threads there are, the more overhead the CPU has on calling threads.
  • Programming is more complex, such as communication between threads, data sharing between multiple threads.

Multithreaded life cycle

The life cycle of multithreading is divided into five parts: new – ready – run – block – death, as shown in the following figure

  • New: Mainly instantiates thread objects

  • Ready: the thread object calls the start method, adds the thread object to the schedulable thread pool, and waits for the CALL of the CPU. That is, the call of the START method will not be executed immediately, and the thread object enters the ready state. It needs to wait for a period of time, and the execution will be executed after the CPU schedule, that is, from the ready state to the running state.

  • Blocking: When a predetermined condition is met, sleep, or a synchronous lock, can be used to block thread execution. When sleep is entered, the thread is re-added to the ready.

  • Death: divided into two cases,

    1. Normal deathThat is, the thread completes execution
    2. Unnatural deathWhen a condition is met, execution terminates inside the thread (or in the main thread) (exit, etc.)
  • Run: a thread executes, and a running thread has a period of time (time slice) that it can execute.

    1. ifTime slice exhausted, the thread will enterReady state queue
    2. ifThe time slot is not used upAnd you need to startWait for something, will enterBlocking status queue
    3. After an event occurs, the thread will re-enterReady state queue
    4. Whenever aThread out of run, that is, after execution or forced exit, a thread is selected from the ready queue to continue execution

The thread pool

The thread pool flow diagram is as follows:

  1. Determine whether the core thread pool is all executing

    • Return NO and create a new worker thread to execute
    • Return YES to enter 2
  2. Determine if the thread pool work queue is full

    • Returns NO and stores the task to a work queue waiting for CPU scheduling
    • Return YES to enter 3
  3. Determines whether the threads in the thread pool are all executing

    • Returns NO to schedule free threads from the schedulable thread pool to execute the task
    • Return YES to enter 4
  4. Leave it to the saturation strategy to execute. There are four types of saturation strategies:

    • AbortPolicy: direct selling RejectedExecutionExeception exceptions to prevent normal operation of system
    • CallerRunsPolicy: rolls back the task to the caller
    • DisOldestPolicy: Drop the most waiting task
    • DisCardPolicy: Directly discards the task
    • All four rejection policies implement the RejectedExecutionHandler interface

Mutexes and spinlocks

Locks are user-protected critical sections, ensuring that only one thread can access a critical section at a time.

spinlocks

  • The spin lock is busy waiting until it gets the resource.
  • Use scenarios for spinlocks: The lock is held for a short time and the thread does not want to spend too much money on re-invocation.OCProperty keywordatomicIt’s using a spin lock.
  • When using a spin lock, if a thread accesses the code and finds that another thread passes to you to lock the code, the new thread will use an infinite loop to wait for the locked code to complete execution, which consumes performance.

The mutex

  • The mutex sleeps until the resource is acquired and wakes up after the resource is released.
  • If the codeThere's only one place to lock, and most of them use selfTo avoid creating a separate lock object
  • The mutexLock in as small a range as possible, the larger the locking range, the worse the efficiency
  • To be able toAny NSObject object that is locked
  • The lock object must be accessible to all threads

Several multithreaded problems

Factors affecting task execution

  • The CPU scheduler
  • The complexity of performing tasks
  • Task priority
  • Thread state

Priority inversion

Two types of threads: IO intensive and CPU intensive

  • IO intensive, frequently waiting threads. It’s easier to get prioritized.
  • CPU intensive, rarely wait threads.
  • IO – intensive threads starve to death.
  • CPU scheduling to increase the priority of waiting threads

Priority factors

  • User specified.
  • The frequency of waiting.
  • Not executing for a long time.