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
process
It refers to an application that is running in the system, such as wechat and Alipay app, which are both a process- each
process
It’s independent of each otherprocess
All run on dedicated and protected memory
2. Definition of threads
thread
isprocess
The basic execution unit of oneprocess
All tasks are executed in the threadprocess
In order to carry out a mission, you have to havethread
.process
Have at least onethread
- Program startup will open one by default
thread
, this articlethread
Known asThe main thread
orThe UI thread
3. The relationship and difference between process and thread
- Address space: same
process
thethread
The address space of each process is shared, while the address space of each process is independent - Resource ownership: Same
process
Within thethread
Share resources such as memory, I/O, CPU, etc. of the process, butprocess
Resources between are independent - a
process
After crash, in protected mode will not work against otherprocess
Make an impact, but onethread
Collapse of the wholeprocess
They’re all dead, soMultiple processes
thanmultithreading
robust process
Switching consumes large resources and is efficient. So design to frequent switching when usingthread
Better than theprocess
. Also, if simultaneous operations are required and some variables are shared, this can only be usedthread
But can’t useprocess
- Execution process: each independent
process
There is a program run entry, sequential execution sequence, and program entry. butthread
Cannot be executed independently, must depend on the application, provided by the applicationthread
Executive control thread
Is the basic unit of processor scheduling, butprocess
not
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
– arunloop
Corresponding to a corethread
Runloops can be nested, but there can only be one core, and their relationship is stored in a global dictionaryRunloop is used to manage threads
— When the threadrunloop
When enabled, the thread will go to sleep after completing the task and will be woken up to execute the taskrunloop
Is created on the first fetch and destroyed at the end of the thread- For the main thread,
runloop
It is created by default as soon as the program starts - For child threads,
runloop
It is lazily loaded — it is created only when we are using it, so beware of using timers in child threads:Ensure that the child threadrunloop
Be createdOtherwise, the timer will not callback
- For the main thread,
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 up
512KB
, creating a thread takes about90 milliseconds
The 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
- Starting threads takes up a certain amount of memory (by default, each thread takes up
2. Multithreaded lifecycle
The life cycle of multithreading is: new – ready – run – block – die
new
: instantiates thread objectsready
: 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.blocking
When 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
- if
Thread pool size
Less thanCore thread pool size
when- Create threads to execute tasks
- if
Thread pool size
Greater than or equal toCore thread pool size
when- Determine whether the thread pool work queue is full
- If not, the task is pushed to the queue
- If it is full and
maximumPoolSize>corePoolSize
, a new thread will be created to execute the task - Otherwise hand over
Saturated strategy
To 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:
AbortPolicy
Direct selling RejectedExecutionExeception exceptions to prevent normal operation of systemCallerRunsPolicy
Roll back the task to the callerDisOldestPolicy
Drop the most waiting taskDisCardPolicy
Drop 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
GCD
Support onlyFIFO
Queues, which do not support dependency Settings between asynchronous operations. whileNSOperation
The queue can be reprioritized to adjust the execution order of different operationsNSOperation
supportKVO
To observe the task execution statusGCD
Closer to the bottom,GCD
It is fastest for low-level operations that seek performance- From transactionality between asynchronous operations, sequential rows, dependencies.
GCD
You have to write more code to do that, andNSOperation
This support is already built in - If the process of asynchronous operations requires more interaction and UI presentation,
NSOperation
Better; In the underlying code, tasks are less interdependent and require more concurrency,GCD
Is more advantageous
6. Communication between threads
Direct messaging
Through:performSelector
A 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 serializedGlobal variables, shared memory blocks, and objects
Another 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 execution
A: 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 efficiencyPorts and sockets
Port-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 portThe 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 technologiesCocoa Distributed Objects
Distributed 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