preface

In the future, you will thank yourself for your efforts now. Every effort is the wealth of the future life road!

Definitions of threads and processes

The concept of time slices

The CPU switches between tasks quickly and directly. This interval is called a time slice

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 tasks, it must have threads, and the process must have at least one thread
  • By default, the program starts a thread, which is called the main thread or UI thread

process

  • A process is an application that is running in the system
  • Each process is independent of each other, and each process runs in a dedicated and protected memory space
  • The Activity Monitor allows you to view processes that are running on the Mac system

The relationship between processes and threads

  • Address space:Threads of the same process share the address space of the same process, while processes are independent of each other.
  • Resources owned:Threads of the same process share memory, I/O, CPU, and other resources of the same process, but resources between processes are independent.
  1. The crash of one process does not affect other processes in protected mode, but the crash of one thread kills the entire process, so multi-process is more robust than multi-thread.
  2. Process switchover consumes large resources and is efficient. When it comes to frequent switching, threads are better than processes. 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 entry and sequential execution sequence. 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. Threads are contained in the process address space.

Meaning of multithreading

  • advantages

  1. Can improve the execution efficiency of the program appropriately
  2. Appropriately improve resource utilization (CPU, memory)
  3. The thread is automatically destroyed after the task is completed
  • disadvantages

  1. Starting threads takes up a certain amount of memory (512KB for each thread by default),
  2. 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
  3. The more threads there are, the more overhead the CPU has on calling threads
  4. The program design is more complex, such as communication between threads, multithreaded data sharing

Principle of multithreading

  • single-core

(Single-core CPU) The CPU can process only one thread at a time. In other words, only one thread is executing at a time

  • multicore

The CPU quickly switches between multiple threads. The CPU schedules threads fast enough to have the effect of “simultaneous” execution by multiple threads.

Four ways to achieve multithreading

Thread life cycle

The concept of thread pools

Saturated strategy

  1. AbortPolicyDirect selling RejectedExecutionExeception exceptions to prevent system normal operation
  2. CallerRunsPolicyThe task is rolled back to the caller
  3. DisOldestPolicyDitch the most waiting tasks
  4. DisCardPolicyDrop the task directly

The purpose of the saturation policy is to discard some tasks according to the task priority and relieve the pressure on the CPU. All four rejection policies implement the RejectedExecutionHandler interface

Factors affecting the speed of task execution

  1. CPU scheduling capability
  2. Task complexity (time complexity, space complexity, etc.)
  3. Task priority
  4. Thread state

Priority reversal

Concept: High-priority tasks are blocked by low-priority tasks, causing high-priority tasks to fail to be scheduled. But other medium-priority tasks can grab CPU resources.

  • IO intensive: threads that wait frequently
  • CPU intensive: threads that rarely wait

In normal cases, the CPU intensive priority is higher than the I/O intensive priority

Priority factor

  1. Priority designation
// User specified, Priority, in turn, reduce the typedef NS_ENUM (NSInteger NSQualityOfService) {NSQualityOfServiceUserInteractive = 0 x21, NSQualityOfServiceUserInitiated = 0x19, NSQualityOfServiceUtility = 0x11, NSQualityOfServiceBackground = 0x09, NSQualityOfServiceDefault = 1} API_AVAILABLE (macos (10.10), the ios (8.0), watchos (2.0), tvos (9.0));Copy the code
  • The frequency of waiting

    If a task is executed frequently, the CPU reduces the priority of the task

  • Not executing for a long time

    If a task is not executed for a long time, the CPU increases the priority of the task

The lock

  • The mutex

In multithreaded programming, a mechanism that prevents two threads from simultaneously reading and writing to the same common resource, such as a global variable. This is achieved by slicing code into critical sections one by one

  • spinlocks

A lock in multithreaded synchronization in which the thread repeatedly checks whether the lock variable is available. Because the thread keeps executing during this process, the current thread keeps busy and so on. The thread acquires the spin lock and holds it until the display releases the spin lock. Spin-locks avoid the scheduling overhead of the process context and are therefore effective in situations where threads block only for short periods of time.

  • Conditions for the lock

A process goes to sleep when some resource requirement is not met, that is, it is locked. When the resource is allocated, the conditional lock is opened and the process continues to execute.

The difference between atomic and nonatomic

  • Nonatomic properties

In its own managed memory environment, the parsed accessor retains and automatically releases the returned value. If nonatomic is specified, the accessor simply returns the value

  • Atomic attributes (thread safety)

Default value designed for multithreading; Ensure that only one thread can write at a time (but multiple threads can write at a time)

Atomic attributes are expensive and consume a lot of resources. Nonatomic is basically used for daily development, because UIKit only allows manipulation of UI elements within threads, since they are only accessed within specified threads; Even if the property is atomic, threads are not necessarily safe.

Thread and Runloop relationship

  1. Runloops correspond to threads one by one. A runloop corresponds to a core thread. Why is the core core
  2. Runloop is used to manage threads. When a thread’s Runloop is enabled, the thread will go to sleep after completing the task and will be woken up to perform the task
  3. The runloop is created on the first fetch and destroyed at the end of the thread
  4. For the main thread, the runloop is created by default as soon as the program starts
  5. For child threads, runloops are lazily loaded and only created when we use them, so be careful when using child timers: make sure the runloop is created for the child thread, otherwise the timer will not call back.