The relevant data

  • Multithreading official documentation

Threads and processes

Definitions of threads and processes

Process of 1.

  • 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.
  • You can view it through the activity monitorMacThe thread that is started in the system.
    • MACIt’s multi-process,iOSIt is single-process.

Thread 2.

  • 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.
  • You can view it through the activity monitorMacThe thread that is started in the system.

The relationship between threads and processes

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 resources (such as memory, I/O, and CPU) in the same process, but resources are independent of each other.

  1. A process crash in protected mode has no impact on other processes, but a thread crash can kill the entire process. So multi-process is more robust than multi-thread.
  2. During process switchover, resources are consumed. When it comes to frequent switching, threads are better than processes. For concurrent operations that require some variables to be shared at the same time, only threads can be used, not 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 and are contained in the process address space.

Two, multithreading

Meaning of multithreading

  • advantages
    1. Appropriately improve the efficiency of execution.
    2. Appropriate utilization of resources (CPU, memory, etc.)
    3. The thread is automatically destroyed after the task is completed.
  • disadvantages
    1. Starting a thread takes up a certain amount of memory (see thread cost below).
    2. Starting a large number of threads occupies a large amount of memory space and reduces program performance.
    3. The more threads,CPUThe greater the overhead in scheduling threads.
    4. Programming is more complex (such as communication between threads, multi-threaded data sharing, etc.).

Principle of multithreading

  • CPUinMultiple tasksbetweenFast switching.

Time slice

The concept of time slice: the time interval between the CPU to switch between multiple tasks is the time slice.

  • A single core CPUAt the same time,CPUCan only handle1A thread
    • In other words, only one time1Three threads are executing.
  • Multithreading simultaneous execution:
    • isCPUFast switching between multiple threads.
    • CPUScheduling threads fast enough creates multithreadingAt the same timeThe effect of execution.
  • CPUWill be inNSwitching between threads consumes a lot ofCPUResources.
  • The number of times each thread is scheduled decreases and the execution efficiency of the thread decreases.

Multithreading must know

Multi-thread technical scheme

Bridge between C and OC

  • __bridgeOnly type conversions are performed, but object (memory) management is not modified.
  • __bridge_retained(Also availableCFBridgingRetain) will beObjective-CObject is converted toCore FoundationAt the same time, the object (memory) management power to us, need to use laterCFReleaseOr related methods to free objects.
  • __bridge_transfer(Also availableCFBridgingRelease) will beCore FoundationObject is converted toObjective-CObject, and give the object (memory) management rightsARC.

Thread life cycle

  • New:newAfter creating a new thread, callstartAfter that, it does not execute immediately. Instead, it enters the ready state and waitsCPUThe scheduling.
  • Run:CPUSchedule the current thread, enter the running state, start to execute the task. If the current thread is running,CPUCall another thread from the schedulable pool to perform this task.
  • Blocking: Running task, invokedsleep/ The synchronization lock is blocked. All threads stop and waitsleepEnd/acquire synchronization lock, will return to the ready state.
  • Dead: A running task. The thread enters automatically when the task is finished or forced to exitDeadDestroyed.

Thread pool scheduling:

Saturation strategy:

  • AbortPolicyDirect sellingRejectedExecutionExeceptionException to prevent the normal operation of the system.
  • CallerRunsPolicyRoll back the task to the caller.
  • DisOldestPolicyDrop the most waiting task.
  • DisCardPolicyThe task is discarded.

All four rejection policies implement the RejectedExecutionHandler interface.

3. Interview questions

Influencing factors of task execution speed

  1. cpuThe scheduling situation of.
  2. Complexity of the task.
  3. Priority.
  4. Thread status.

Priority reversal

  1. IOIntensive, frequently waiting threads, prone to starvation, will have priority increases.
  2. CPUIntensive, rarely wait threads.

Priority factors

  1. User specified.
    typedef NS_ENUM(NSInteger, NSQualityOfService) {
        NSQualityOfServiceUserInteractive = 0x21,
        NSQualityOfServiceUserInitiated = 0x19,
        NSQualityOfServiceUtility = 0x11,
        NSQualityOfServiceBackground = 0x09,
        NSQualityOfServiceDefault = -1
    }
    Copy the code
  2. The frequency of waiting.
  3. If the command is not executed for a long time, its priority is increased.

Spin locks and mutex

When multi-window tickets are sold, as shown in the figure below, there is a resource grab, and our normal operation is locking.

Exclusive locks:

  1. Ensure that only one thread can execute the code in the lock at a time.
  2. The lock range of a mutex should be as small as possible. The greater the lock range, the worse the efficiency.

Mutex parameters:

  1. Any that can be lockedNSObjectObject.
  2. The lock object must be accessible to all threads.
  3. If only one part of the code needs to be locked, use most of themselfTo avoid creating a separate lock object.

The spin lock.

  1. Consumption of performance, whether the cycle can be executed. Spin lock content should be as small as possible to ensure the completion of lock tasks as soon as possible.

The difference between a mutex and a spin lock:

  • The mutexisPassive waiting forCode triggers and locks.
    • requirementsExecuted immediately, set this parameter when the task resources are small and the execution time is shortspinlocks.
  • spinlocksisActive round-robin requesting resources. soSpin locks consume more resources.
    • Passive trigger.Large task resources (long execution time)When choosingThe mutex.

The difference between atomic and nonatomic

  • nonatomic: Non-atomic, non-thread-safe, suitable for mobile devices with small memory.
  • atomic: Atomic property, thread safe, consumes a lot of resources, is the default.
  • atomic: is designed for multithreading, with its own spin lock, to achieve single-write multi-read (a single thread write, multiple threads can read).

IOS official recommendations:

  • All properties are declared asnonatomicTo prevent multiple threads from grabbing the same resource.
  • Try to transfer the service logic of locking and resource snatching to the server to reduce the pressure on mobile clients.

Thread and RunLoop

  1. RunLoopwiththreadisOne to one correspondenceThe,A runloopThe correspondingA coreThe thread. Why is it core, becauserunloopCan be nested, but the core can only have one, and their relationship is kept in oneGlobal dictionaryIn the water.
  2. RunloopIs toManagement of threadOf, when threadedrunloopAfter it is enabled, the thread will go to sleep after completing the task, and it will wake up to execute the task.
  3. RunloopIs created on the first fetch and destroyed at the end of the thread.
  4. forThe main threadSpeaking,runloopIn the program aStart theitCreated by defaultAll right.
  5. forThe child threadSpeaking,runloopisLazy loadingThe timer will only be created when we use it, so be careful when using the timer in the child thread: make sure that the child threadrunloopWas created, or the timer will not be called back.