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 monitor
Mac
The thread that is started in the system.MAC
It’s multi-process,iOS
It 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 monitor
Mac
The 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.
- 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.
- 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.
- 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.
- Threads are the basic unit of processor scheduling, but processes are not.
- Threads have no address space and are contained in the process address space.
Two, multithreading
Meaning of multithreading
- advantages
- Appropriately improve the efficiency of execution.
- Appropriate utilization of resources (
CPU
, memory, etc.) - The thread is automatically destroyed after the task is completed.
- disadvantages
- Starting a thread takes up a certain amount of memory (see thread cost below).
- Starting a large number of threads occupies a large amount of memory space and reduces program performance.
- The more threads,
CPU
The greater the overhead in scheduling threads. - Programming is more complex (such as communication between threads, multi-threaded data sharing, etc.).
Principle of multithreading
CPU
inMultiple tasks
betweenFast 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 CPU
At the same time,CPU
Can only handle1
A thread- In other words, only one time
1
Three threads are executing.
- In other words, only one time
- Multithreading simultaneous execution:
- is
CPU
Fast switching between multiple threads. CPU
Scheduling threads fast enough creates multithreadingAt the same time
The effect of execution.
- is
CPU
Will be inN
Switching between threads consumes a lot ofCPU
Resources.- 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
__bridge
Only type conversions are performed, but object (memory) management is not modified.__bridge_retained
(Also availableCFBridgingRetain
) will beObjective-C
Object is converted toCore Foundation
At the same time, the object (memory) management power to us, need to use laterCFRelease
Or related methods to free objects.__bridge_transfer
(Also availableCFBridgingRelease
) will beCore Foundation
Object is converted toObjective-C
Object, and give the object (memory) management rightsARC
.
Thread life cycle
- New:
new
After creating a new thread, callstart
After that, it does not execute immediately. Instead, it enters the ready state and waitsCPU
The scheduling. - Run:
CPU
Schedule the current thread, enter the running state, start to execute the task. If the current thread is running,CPU
Call another thread from the schedulable pool to perform this task. - Blocking: Running task, invoked
sleep
/ The synchronization lock is blocked. All threads stop and waitsleep
End/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 exit
Dead
Destroyed.
Thread pool scheduling:
Saturation strategy:
AbortPolicy
Direct sellingRejectedExecutionExeception
Exception to prevent the normal operation of the system.CallerRunsPolicy
Roll back the task to the caller.DisOldestPolicy
Drop the most waiting task.DisCardPolicy
The task is discarded.
All four rejection policies implement the RejectedExecutionHandler interface.
3. Interview questions
Influencing factors of task execution speed
cpu
The scheduling situation of.- Complexity of the task.
- Priority.
- Thread status.
Priority reversal
IO
Intensive, frequently waiting threads, prone to starvation, will have priority increases.CPU
Intensive, rarely wait threads.
Priority factors
- User specified.
typedef NS_ENUM(NSInteger, NSQualityOfService) { NSQualityOfServiceUserInteractive = 0x21, NSQualityOfServiceUserInitiated = 0x19, NSQualityOfServiceUtility = 0x11, NSQualityOfServiceBackground = 0x09, NSQualityOfServiceDefault = -1 } Copy the code
- The frequency of waiting.
- 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:
- Ensure that only one thread can execute the code in the lock at a time.
- The lock range of a mutex should be as small as possible. The greater the lock range, the worse the efficiency.
Mutex parameters:
- Any that can be locked
NSObject
Object. - The lock object must be accessible to all threads.
- If only one part of the code needs to be locked, use most of them
self
To avoid creating a separate lock object.
The spin lock.
- 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 mutex
isPassive waiting for
Code triggers and locks.- requirements
Executed immediately
, set this parameter when the task resources are small and the execution time is shortspinlocks
.
- requirements
spinlocks
isActive 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 as
nonatomic
To 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
RunLoop
withthread
isOne to one correspondence
The,A runloop
The correspondingA core
The thread. Why is it core, becauserunloop
Can be nested, but the core can only have one, and their relationship is kept in oneGlobal dictionary
In the water.Runloop
Is toManagement of thread
Of, when threadedrunloop
After it is enabled, the thread will go to sleep after completing the task, and it will wake up to execute the task.Runloop
Is created on the first fetch and destroyed at the end of the thread.- for
The main thread
Speaking,runloop
In the program aStart the
itCreated by default
All right. - for
The child thread
Speaking,runloop
isLazy loading
The 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 threadrunloop
Was created, or the timer will not be called back.