Threads and Processes
1, define,
process
- A process is an application that is running on the system
- Interprocess
Are independent of each other
, each running in its own dedicated and protected memory space (sandbox) - Activity Monitor allows you to view all processes on your Mac (with a small icon in the front to indicate desktop permissions)
- IOS and Android have multiple processes (which can communicate between processes), iOS
Apps are single-process
thread
- Threads are processes
Basic execution unit
, all tasks of the process are assigned to the thread - By default, the program opens a main thread, also known as the UI thread
The relationship between processes and threads
Address space
: Threads of the same process share the address space of the same process, but the address space between processes is independent (threads can only use the address space of the process).Resources have
: Threads in the same process share resources such as memory, I/O, and CPU of the process, but the resources between the processes are independent.
Supplement:
- When a process crashes, it does not affect other processes in protected mode, but when a thread crashes, the entire process dies. So multiple processes are more robust than multiple threads.
- When the process switches,
It consumes a lot of resources
, high efficiency. So when switching frequently, it’s better to use threads than processes. Similarly, if concurrent operations are required simultaneously and share some variables, only threads can be used, not processes - Execution process: Each independent process has a program running entry, sequential execution sequence and program entry. However, threads cannot be executed independently, and must be dependent on the application program, which provides multiple thread execution control.
- The thread is
The basic unit of processor scheduling
But the process is not. - Threads have no address space,
Threads are contained in the process address space
- TLS: Local thread staging space. The local storage space of a thread is a private space provided by the system for the thread. It usually has limited capacity and is not part of the thread
2. Advantages and disadvantages of multithreading
Advantages:
- Can properly improve the efficiency of program execution
- Appropriate resource utilization (CPU, memory)
- When the tasks on the thread finish executing, the thread automatically destroys
Disadvantages:
- Starting threads requires a certain amount of memory space (default)
Each thread is 512KB, 90ms
Time) - If a large number of threads are enabled, a large amount of memory space is occupied and program performance is degraded
- The more threads there are, the greater the CPU overhead on the calling thread
- The program design is more complex, such as communication between threads, multi-threaded data sharing and so on
3, the principle of multithreading
Time slice
: The CPU quickly switches between tasks. This interval is called time slicing
- (Single-core CPU) The CPU can only process one thread at a time. In other words, only one thread is executing at a time
- Multithreaded execution
- The CPU quickly switches between multiple threads
- The CPU schedules the threads quickly enough to create the effect of “simultaneous” execution
- When there are many threads
- The CPU switches between N threads, which consumes a lot of CPU resources
- The number of times each thread is scheduled is reduced and the execution efficiency of the thread is reduced
4. Multithreading is the logical layer concept of programming
Multithreaded data
Bridge between C and OC
- ‘__bridge’ only does type conversions, but
Do not modify object (memory) management rights
- ‘__bridge_retained’ (you can also use ‘CFBridgingRetain’)
Convert an object-c Object to a Core Foundation Object
At the same time, the management of the object (memory) will be handed over to usUse CFRelease or related methods to release the object
- ‘__bridge_transfer’ (you can also use ‘CFBridgingRelease’)
Convert a Core Foundation object to an Objective-C object
And give the management of the object (memory) to ARC
Thread life cycle
- The multithreaded life cycle is divided into five main parts: new – Ready – Run – Block – Death
-
New: Instantiates the thread object
-
Ready: The thread object calls the start method, adds the thread object to the schedulable thread pool, waits for the CPU call (that is, calls the start method), does not execute immediately, enters the ready state, needs to wait for a period of time, after the CPU time slice scheduling, then executes, that is, from the ready state to the running state.
-
Block: When a predetermined condition is met, sleep can be used, or a synchronization lock can be used to block the thread from executing. When you enter sleep, the thread is re-added to the thread pool.
-
Death: Divided into two conditions,
Normal death
, that is, the thread completes executionUnnatural death
When a condition is met, the execution is terminated inside the thread (or in the main thread) (exit method is called, etc.)
-
Run: Thread execution, in which a running thread has a period of time (time slice) to execute.
- if
Time slice run out
, the thread will enterReady status queue
- if
The time slice didn't run out
And you need to startWait for an event
, will enterBlocking status queue
- After waiting for the event to occur, the thread will re-enter
Ready status queue
- Whenever a
Thread off run
That is, after the execution is completed or forced to exit, a thread will be selected from the ready status queue to continue the execution
- if
5. Thread pool
- Check whether the core thread has idle threads — Check whether the thread pool is full (the thread pool capacity has a threshold) — Check whether the thread pool has idle threads — Saturation policy
Saturated strategy
AbortPolicy
: direct selling RejectedExecutionExeception exceptions to prevent normal operation of system (reported)CallerRunsPolicy
: Roll back the task to the caller (no processing)DisOldestPolicy
: Discard the longest-waiting task (discard useless threads)DisCardPolicy
: Discard tasks directly (discard threads)- These four rejection strategies all implement the RejectedExecutionHandler interface
6. Spin locks and mutexes
A lock is a user-protected critical section that ensures that only one thread can access the critical section at a time.
spinlocks
- The spinlock is busy waiting until the resource is acquired.
- Use scenarios of spin locks:
Lock holding time is short
For short content, and the thread does not want to spend too much money on recalls. The keyword of the OC attributeatomic
You use a spin lock. - With spin-locking, be careful that if a thread accesses code and another thread sends you the locked code, the new thread will use an infinite loop, waiting for the locked code to complete, and comparing performance costs.
The mutex
Summary of mutex
- Ensure that the code in the lock is executed by only one thread at a time
- The mutex
Lock range, should be as small as possible
, the greater the locking range, the worse the efficiency
Mutex parameters
- To be able to
Any NSObject that is locked
- The lock object must be accessible to all threads
- If the code
There's only one place you need to lock it, and most of them use self
To avoid creating a separate lock object - The mutex is dormant until the resource is acquired, and will be awakened when the resource is released.
7. The difference between atomic and nonatomic
- nonatomic:
- Nonatomic property
- Non-thread safe, suitable for mobile devices with small memory
- atomic :
- Atomic property (thread-safe), designed for multiple threads, default
- Ensure that only one thread can write at a time (but multiple threads can write at the same time, which can also cause thread safety issues),
- Atomic has its own lock (spin-lock)
Write read alone
: A single thread can write, and multiple threads can read- It takes a lot of resources
- Atomic and nonatomic are just an indication of whether the internal code is locked
objc-accessors.mm : if (! atomic) { oldValue = *slot; *slot = newValue; } else { spinlock_t& slotlock = PropertyLocks[slot]; slotlock.lock(); oldValue = *slot; *slot = newValue; slotlock.unlock(); }Copy the code
IOS development advice for both
- All properties are declared nonatomic
- Avoid multiple threads snatching the same resource
- Transfer the service logic of locking and resource grabbing to the server as much as possible to reduce the pressure on the mobile terminal
8. Relationship between thread and Runloop
- Runloops correspond to threads one to one,
A runloop corresponds to a core thread
Why core? BecauseRunloops can be nested
But there is only one core, and their relationships are stored in a global variable dictionary - Runloop is used to manage threads. When a thread’s runloop is enabled, the thread will go to sleep after executing a task, and will wake up to execute the task
- The runloop is created on the first fetch and destroyed when the thread ends
- For the main thread, the runloop is created by default as soon as the program starts
- For a child thread,
Runloop is lazily loaded
It will only be created when we use it, so make sure the runloop is created for the child thread, otherwise the timer will not be called back
9. Priority reversal
Influencing factors of task execution
- The CPU scheduler
- The complexity of the execution task
- Priority of tasks
- Thread state
Priority reversal
There are two types of threads: IO – intensive (IN and OUT) and CPU – intensive
- IO intensive, frequently waiting threads. More likely to be prioritized.
- CPU intensive, few waiting threads.
- IO – intensive threads tend to starve.
- CPU scheduling to increase the priority of waiting threads
The influencing factors of priority
- User specified.
- The frequency of waiting.
- No execution for a long time.