Welcome to the iOS Exploration series.

  • IOS explores the alloc process
  • IOS explores memory alignment &malloc source code
  • IOS explores ISA initialization & pointing analysis
  • IOS exploration class structure analysis
  • IOS explores cache_T analysis
  • IOS explores the nature of methods and the method finding process
  • IOS explores dynamic method resolution and message forwarding mechanisms
  • IOS explores the dyLD loading process briefly
  • The loading process of iOS explore classes
  • IOS explores the loading process of classification and class extension
  • IOS explores isa interview question analysis
  • IOS Explore Runtime interview question analysis
  • IOS explores KVC principles and customization
  • IOS explores KVO principles and customizations
  • IOS explores the principle of multithreading
  • IOS explores multi-threaded GCD applications
  • IOS explores multithreaded GCD underlying analysis
  • IOS explores NSOperation for multithreading
  • IOS explores multi-threaded interview question analysis
  • IOS Explore the locks in iOS
  • IOS explores the full range of blocks to read

Writing in the front

Multithreading plays an important role in iOS. Do not think that UI does not need to understand threads. It can not only boast about them in interviews, but also ensure the quality of app when used properly

Processes, threads, and queues

1. Process definition

  • processIt refers to an application that is running in the system, such as wechat and Alipay app, which are both a process
  • eachprocessIt’s independent of each otherprocessAll run on dedicated and protected memory

2. Definition of threads

  • threadisprocessThe basic execution unit of oneprocessAll tasks are executed in the thread
  • processIn order to carry out a mission, you have to havethread.processHave at least onethread
  • Program startup will open one by defaultthread, this articlethreadKnown asThe main threadorThe UI thread

3. The relationship and difference between process and thread

  • Address space: sameprocessthethreadThe address space of each process is shared, while the address space of each process is independent
  • Resource ownership: SameprocessWithin thethreadShare resources such as memory, I/O, CPU, etc. of the process, butprocessResources between are independent
  • aprocessAfter crash, in protected mode will not work against otherprocessMake an impact, but onethreadCollapse of the wholeprocessThey’re all dead, soMultiple processesthanmultithreadingrobust
  • processSwitching consumes large resources and is efficient. So design to frequent switching when usingthreadBetter than theprocess. Also, if simultaneous operations are required and some variables are shared, this can only be usedthreadBut can’t useprocess
  • Execution process: each independentprocessThere is a program run entry, sequential execution sequence, and program entry. butthreadCannot be executed independently, must depend on the application, provided by the applicationthreadExecutive control
  • threadIs the basic unit of processor scheduling, butprocessnot

May feel that these theoretical knowledge is very abstract, Baidu out of a lot of but are not easy to understand, read the following understanding will be fully understood

4. Process and thread diagram

iOS
The mall
process
The store
thread
employees

  • Independence of processes from one another
    • Milk tea shop can’t see juice shop’s account (can’t access memory of other processes)
    • – Juice shop can no longer use milk tea shop’s boobs (resources are independent between processes)
  • A process must have at least one thread
    • Store must have at least one employee (processes must have at least one thread)
    • Morning opening staff (equivalent to the main thread)
  • A process/thread crash
    • Failure of milk tea shop does not affect failure of juice shop (process crash does not affect other processes)
    • [Bug Mc-10821] – Milk tea shop cashiers quit, causing the shop to not function properly (thread crash causes process to crash)

Mobile development doesn’t have to be single-process, Android is multi-process; IOS is sandbox, which is one of the main reasons why Apple runs smoothly and safely

5. Definition of queues

Queue, also known as queue, is a linear FIFO (first-in-first-out) list. In specific applications, it is realized by linked list or array. Load the queue structure of threaded tasks. Queues only allow insertion at the back end (called rear) and deletion at the front (called front). Queues operate like stacks, except that queues allow only new data to be added at the back end

More on queues in the next article

6. Relationship between queues and threads

There is no relation between the two.

  • Queues are responsible for scheduling tasks, and threads execute tasks

  • In the bank (process), there are four worker Windows (threads) and only one queue (queue)

  • The window (thread) is only responsible for the queue of people to do business, does not care about the queue (queue)

7. Thread and runloop relationship

  • Runloops correspond to threads one by one– arunloopCorresponding to a corethreadRunloops can be nested, but there can only be one core, and their relationship is stored in a global dictionary
  • Runloop is used to manage threads— When the threadrunloopWhen enabled, the thread will go to sleep after completing the task and will be woken up to execute the task
  • runloopIs created on the first fetch and destroyed at the end of the thread
    • For the main thread,runloopIt is created by default as soon as the program starts
    • For child threads,runloopIt is lazily loaded — it is created only when we are using it, so beware of using timers in child threads:Ensure that the child threadrunloopBe createdOtherwise, the timer will not callback

8. Factors affecting the speed of task execution

The following factors will affect the execution speed of the task:

  • The CPU scheduler
  • The execution rate of the thread
  • The queue is
  • Complexity of task execution
  • Task priority

Two, multithreading

1. Principle of multi-threading

  • The CPU can only process one thread at a time, and only one thread is working (executing)
  • Multi-threaded concurrent execution is when CPU execution is scheduled (switched) between multiple threads very quickly

2. Significance of multi-threading

  • advantages
    • Can improve the execution efficiency of the program
    • Appropriately improve resource utilization (CPU, memory)
    • The task on the thread is automatically destroyed after it completes execution
  • disadvantages
    • Starting threads takes up a certain amount of memory (by default, each thread takes up512KB, creating a thread takes about90 millisecondsThe creation time of
    • 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
    • The program design is more complex, such as communication between threads, multithreaded data sharing

2. Multithreaded lifecycle

The life cycle of multithreading is: new – ready – run – block – die

  • new: instantiates thread objects
  • ready: Sends a start message to the thread object, which is added to the pool of schedulable threads waiting for CPU scheduling.
  • run: THE CPU is responsible for scheduling the execution of threads in the schedulable thread pool. Before the thread completes execution, the state may switch back and forth between ready and run. State changes between ready and run are the responsibility of the CPU, not the programmer.
  • blockingWhen a predetermined condition is met, sleep or lock can be used to block thread execution.sleepForTimeInterval(Specified sleep duration),sleepUntilDate(Sleep until the specified date),@ synchronized (self) :(Mutex).
  • death: Normal death, thread execution complete. Unnatural death, aborting execution inside a thread/aborting a thread object in the main thread when a condition is met

4. Thread pool principle

  • ifThread pool sizeLess thanCore thread pool sizewhen
    • Create threads to execute tasks
  • ifThread pool sizeGreater than or equal toCore thread pool sizewhen
    1. Determine whether the thread pool work queue is full
    2. If not, the task is pushed to the queue
    3. If it is full andmaximumPoolSize>corePoolSize, a new thread will be created to execute the task
    4. Otherwise hand overSaturated strategyTo deal with
Parameter names On behalf of the meaning
corePoolSize Base size of the thread pool (core thread pool size)
maximumPool The maximum size of the thread pool
keepAliveTime The maximum lifetime of idle threads in the thread pool that exceed the corePoolSize tree
unit KeepAliveTime Indicates the time unit of the parameter
workQueue Task blocking queue
threadFactory Create a factory for the thread
handler When the number of submitted tasks exceeds the sum of maxmumPoolSize and workQueue,

The task will be handled by RejectedExecutionHandler

There are four saturation strategies as follows:

  • AbortPolicyDirect selling RejectedExecutionExeception exceptions to prevent normal operation of system
  • CallerRunsPolicyRoll back the task to the caller
  • DisOldestPolicyDrop the most waiting task
  • DisCardPolicyDrop the task directly

4. Multi-thread implementation scheme

Technical solution Introduction to the language Thread life cycle Using a review of the rate
pthread A set of generic multithreading apis

It is applicable to Unix, Linux, and Windows

Cross-platform/portable

Difficult to use
C Programmer management Almost no
NSThread Use more object-oriented

Easy to use, direct manipulation of thread objects
OC Programmer management Occasionally use
GCD Designed to replace threading technologies such as NSThreads

Take full advantage of multi-core equipment
C Automatic management Often use
NSOperation Based on GCD (underlying is GCD)

More than GCD some more simple and practical functions

Use more object-oriented
OC Automatic management Often use

5. Difference between GCD and NSOperation

  • GCDSupport onlyFIFOQueues, which do not support dependency Settings between asynchronous operations. whileNSOperationThe queue can be reprioritized to adjust the execution order of different operations
  • NSOperationsupportKVOTo observe the task execution status
  • GCDCloser to the bottom,GCDIt is fastest for low-level operations that seek performance
  • From transactionality between asynchronous operations, sequential rows, dependencies.GCDYou have to write more code to do that, andNSOperationThis support is already built in
  • If the process of asynchronous operations requires more interaction and UI presentation,NSOperationBetter; In the underlying code, tasks are less interdependent and require more concurrency,GCDIs more advantageous

6. Communication between threads

  • Direct messagingThrough:performSelectorA set of methods for executing tasks specified by one thread on another. Since the execution context of the task is the target thread, messages sent in this manner will be automatically serialized
  • Global variables, shared memory blocks, and objectsAnother simple way to pass information between two threads is to use global variables, shared objects, or shared chunks of memory. Although shared variables are fast and easy, they are more fragile than direct messaging. Shared variables must be carefully protected using locks or other synchronization mechanisms to ensure correct code. Failure to do so may result in competitive conditions, data corruption, or crashes.
  • Conditional executionA: condition is a synchronization tool that can be used to control when a thread executes a particular part of code. You can treat a condition as a lock and let the thread run only when the specified condition is met.
  • Runloop sources: A custom Runloop source configuration allows specific application messages to be received on a thread. Because Runloop sources are event-driven, threads automatically go to sleep when there is nothing to do, increasing thread efficiency
  • Ports and socketsPort-based communication is a more sophisticated way of communicating between two threads, but it is also a very reliable technique. More importantly, ports and sockets can be used to communicate with external entities, such as other processes and services. To improve efficiency, the port is implemented using a Runloop source, so the thread goes to sleep when there is no data waiting on the port
  • The message queue: Traditional multiprocessing services define a first-in, first-out (FIFO) queue abstraction for managing incoming and outgoing data. Although message queues are simple and convenient, they are not as efficient as some other communication technologies
  • Cocoa Distributed ObjectsDistributed objects are a Cocoa technology that provides a high-level implementation of port-based communication. Although it is possible to use this technique for interthread communication, it is strongly recommended not to do so because of the overhead involved. Distributed objects are better suited for communicating with other processes, although transactions between these processes are also expensive

Write in the back

This article introduces multithreading preliminarily, the next article explains the protagonist of multithreading – GCD