preface
Short step without thousands of miles, not small streams into rivers and seas. Learning is like rowing upstream; not to advance is to drop back. I’m a hauler who drifts from platform to platform. Study half an hour a day, health and happiness for a lifetime. Today I’m going to talk about UI related interview questions. Nonsense not to say, directly to everyone dry goods, I hope to help you, excellent people have been praised.
I. Process:
1. Process is a program with a certain independent function about a data set of a running activity, it is the operating system allocation resources
The base unit of the source.
2. Process refers to an application that is running in the system, which is the execution process of a program. We can understand it as a mobile phone
One of the app.
3. Each process is independent of each other. Each process runs in its dedicated and protected memory space and has requirements for independent running
The total resources of
Second, the thread
1. The smallest unit of a program’s execution flow. A thread is an entity in a process.
2. To execute a task, a process must have at least one thread. When the application starts, the system starts a thread by default,
That’s the main thread
The relationship between process and thread
1. A thread is the execution unit of a process. All tasks of a process are executed in a thread
2. Thread is the minimum unit of CPU resource allocation and scheduling
3. A program can correspond to multiple processes (multi-process). There can be multiple threads in a process, but there must be at least one thread
4. Threads in the same process share process resources
4. Multiple processes
Turn on the MAC’s activity monitor and you can see many song processes running at the same time
-
A process is an execution activity of a program on a computer. When you run a program, you start a process. Obviously, the program
Is dead (static), the process is alive (dynamic).
-
Processes can be divided into system processes and user processes. The process used to complete the various functions of the operating system is the system process, it
They are the operating system itself in operation; All processes started by the user are user processes. Processes are operating system inputs
The unit of row resource allocation.
-
Processes are subdivided into threads, which are smaller units of a process that can run independently. At the same time, with
A computer system that allows two or more processes to be running is called multi-process.
Five, multi-threading
1. The CPU can process only one thread at a time, and only one thread is executing. When multiple threads execute concurrently, the CPU schedules (switches) between multiple threads quickly. If the CPU schedules threads fast enough, it creates the illusion that multiple threads are executing concurrently
- If there are very, very many threads, the CPU will schedule between N threads, consuming a lot of CPU resources, the number of times each thread is scheduled to execute
Reduces (thread execution efficiency)
- Advantages of multi-threading:
Can improve the execution efficiency of the program
Appropriately improve resource utilization (CPU, memory utilization)
- Disadvantages of multithreading:
By default, the main thread occupies 1 MB and child threads occupy 512KB. If a large number of threads are enabled, the memory space is required
Threads take up a lot of memory space and reduce the performance of the program
The more threads there are, the more overhead the CPU has on scheduling threads
Programming is more complex: communication between threads, data sharing between multiple threads
Six, task,
It means to perform an operation, which is the piece of code that executes in a thread. In GCD it is placed in a block. There are two kinds of missions
Mode: Sync and Async
Sync: Synchronously adds a task to a specified queue. The system waits until the task is completed in the queue
Continuing to execute a task after completion blocks the thread. Can only execute tasks in the current thread (the current thread, not necessarily the main thread),
Does not have the ability to start new threads.
Async: The thread returns immediately and continues to perform the following tasks without waiting, without blocking the current thread. It can be in a new thread
Perform tasks with the ability to start new threads (not necessarily). If not added to the main queue, asynchrony is in the child thread
Perform a task
Seven, queue
Dispatch Queue: The Queue refers to the waiting Queue for executing tasks, that is, the Queue for storing tasks. A queue is a special linear table that uses FIFO (first in, first out), meaning that new tasks are always inserted at the end of the queue and read from the head of the queue. There are two types of queues in the GCD: serial queue and concurrent queue. Both comply with FIFO (first in, first out). The main differences between the two are: the execution order is different, and the number of threads started is different.
– Serial Dispatch Queue:
Only one task can be executed in a queue at a time. The next task can be executed only after the current task is completed. (only
Start a thread and execute the next task after completing one task. The main queue is a serial queue on the main thread
The system created it for us automatically
– Concurrent Dispatch Queue:
Multiple tasks can be executed concurrently. (Multiple threads can be started and tasks can be executed simultaneously). The concurrency function of the concurrent queue is only
Only valid for asynchronous (dispatch_async) functions
Multithreading in iOS
There are three main types: NSThread, NSoperationQueue, and GCD
1.NSThread: Lightweight multi-threading technology
It’s the child thread that we manually start, and if we use initialization we need to start it ourselves, if we use constructor
It will start automatically. As long as we manually open the thread, we need to manage the thread, not only start the thread, but also enable the thread
Recycling of resources after use
Note that if it is a delay function with afterDelay, an NSTimer is created internally and then added to the current thread’s
In the Runloop. That is, if runloop is not enabled on the current thread, the method will be disabled. In child threads, you need to start runloop
Call order)
2. Compare GCD with NSOprationQueue
We want to clarify the relationship between NSOperationQueue and GCD
GCD is an API for the underlying C language. NSOpertaionQueue is a high-level abstraction of GCD built and encapsulated by GCD.
1. GCD performs more efficiently, and since the queue performs tasks made up of blocks, it is a lightweight data structure, write up
To more convenient
2. GCD only supports FIFO queues, while NSOperationQueue can be set by setting the maximum number of concurrent requests, setting the priority, and adding dependencies
Adjust the execution sequence
NSOperationQueue can even be set up across queues, but GCD can only set up serial queues, or add within queues
Add barrier(dispatch_barrier_async) tasks to control the execution order
NSOperationQueue (object oriented) supports KVO to monitor whether operation isExecuted.
Whether to end (isFinished), whether to cancel (isCanceld)
-
In actual project development, a lot of time will only use asynchronous operations, not particularly complex thread relationship management, so Apple advocates
And optimized, fast running GCD is the first choice
-
If you consider transactionality, sequential rows, dependencies between asynchronous operations, such as multi-threaded concurrent downloads, GCDS need to write more themselves
And NSOperationQueue already has this support built in
-
Whether it’s GCD or NSOperationQueue, we’re dealing with tasks and queues, we’re not dealing directly with threads, actually
Thread management does not need to be worried about, the system for thread creation, scheduling management and release do a good job. The NSThread
We need to manage the life cycle of threads ourselves, and consider thread synchronization and locking, causing some performance overhead
9. Communist Party — The queue
In iOS, there are several multi-threaded technology schemes such as GCD, NSOperation and NSThread.
The GCD has three queue types:
Main queue: obtained via dispatch_get_main_queue(), which is a serial queue associated with the main thread.
Global Queue: A global queue is a concurrent queue shared by the entire process. There are global queues with high, middle, and low priorities. call
Dispath_get_global_queue and pass in the priority to access the queue.
Custom queues: queues created using the dispatch_queue_create function
Ten, deadlocks
A deadlock is a circular wait caused by a queue
1. A common example of deadlock: primary queue synchronization
2. The following code also causes a deadlock:
Xi GCD task execution sequence
1. Serial queues are asynchronous and then synchronized
Twelve, dispatch_barrier_async
1. Q: How to use GCD to achieve multiple read and write?
Multi-read single-write means that multiple readers can read data at the same time, while reading, can not read and write data. And, in the process of writing
In, no other writer can write. That is, readers are concurrent, and writers are mutually exclusive with readers or other writers.
The writing process here is to write through the fence.
This can be done with dispatch_barrier_sync
2, dispatch_barrier_sync
The dispatch_barrier_sync queue is invalid unless it is on the same queue as the task that needs to block.
From the print, tasks 0-9 and 10-19 are out of order because they are asynchronous and concurrent. And because of the fence function,
The resulting sequence must be task 0-9, then fence function, then task 10-19.
- dispatch_barrier_sync: Submits a barrier block object for execution and waits until that
In the process of completing a fence function, it will wait for the fence function to complete.
- dispatch_barrier_async: Submits a barrier block for asynchronous execution and returns
(Submit a fence function in asynchronous execution, it will return immediately)
The difference between dispatch_barrier_sync and dispatch_barrier_async is that it blocks the current thread
For example, if dispatch_barrier_async is followed by a print, the print will be executed first and then executed
Line tasks 0-9 and fence functions; With dispatch_barrier_sync, this is done after tasks 0-9 and the fence function
The print.
3, can be designed like this:
13, dispatch_group_async
Dispatch Semaphore
A GCD Semaphore is a Dispatch Semaphore, a signal that holds counts.
Dispatch Semaphore provides three functions
1. Dispatch_semaphore_create: creates a Semaphore and initializes the total number of signals
2. Dispatch_semaphore_signal: dispatch_semaphore_signal: send a signal
3. Dispatch_semaphore_wait: the number of dispatch_semaphore_wait is reduced by 1. If the number of dispatch_semaphore_wait is 0, the system waits (blocking thread)
Then it can be executed normally.
Dispatch Semaphore is mainly used in practical development for:
-
Keep thread synchronization and convert asynchronous execution tasks to synchronous execution tasks
-
Keep the thread safe and lock the thread
1. Keep threads synchronized:
2, to ensure thread safety, thread lock:
Here’s why:
If asyncTask is executed concurrently in a child thread, the first one added to the concurrent queue will decrease the semaphore by one, so that the semaphore is equal to zero.
You can perform the following tasks. Other tasks in the concurrent queue, since the semaphore is not equal to 0, must wait for the currently executing task
After the execution is complete, call dispatch_semaphore_signal and add 1 to the semaphore. Then you can continue to perform the following tasks, and so on
To achieve the purpose of thread locking.
Delay function (dispatch_after)
16. Use dispatch_once to implement singleton
Advantages of NSOperationQueue
NSOperation and NSOperationQueue are multi-threaded solutions provided by Apple. In fact, NSOperation,
NSOperationQueue is a higher level wrapper based on GCD and is fully object-oriented. But it is easier to use and more readable than GCD
Is also higher.
1. Task dependencies can be added to facilitate the control of the execution sequence
2. You can set the priority of the operation
3, task execution status control: isReady, isExecuting, isFinished, isCancelled
If the main method of NSOperation is simply overridden, the low-level control changes the execution and completion status of the task, and the task exits
If the start method of NSOperation is overridden, the task state is controlled by itself
The system uses KVO to remove the NSOperation of isFinished==YES
3. You can set the maximum concurrency
NSOperation and NSOperationQueue
Operation:
By executing an operation, in other words, that piece of code that you execute in a thread.
In GCD it is placed in a block. In NSOperation, use the NSOperation subclass
NSInvocationOperation,
NSBlockOperation, or a custom subclass to encapsulate operations.
Operation Queues:
The queue here refers to the operation queue, which is used to store operations. Different from scheduling queues in GCD
FIFO (first in first out).
NSOperationQueue First enters the ready state for operations added to the queue (ready state depends on the dependencies between operations
Relationship), and then the start execution order (non-end execution order) of the operations that enter the ready state is determined by the relative priority of the operations (excellent)
The first level is the property of the operation object itself. Operation queue by setting the maximum number of concurrent operation (maxConcurrentOperationCount) to control the concurrency, serial.
NSOperationQueue provides us with two different types of queues: primary queue and custom queue. The main queue runs on the main thread,
Custom queues execute in the background.
NSThread+runloop
A common scenario for nsthreads in real life development is to implement resident threads.
- Since CPU is consumed each time a child thread is opened, frequent child threads can consume a large amount of time when child threads need to be used frequently
CPU, and create thread is the task after the completion of the release, can not be used again, so how to create a thread can
Make it work again? That is, create a resident thread.
First, resident threads since resident threads are resident, we can use GCD to implement a singleton to hold nsThreads
Spin locks and mutex
The spin lock.
Is a lock used to protect multithreaded shared resources. It differs from mutex in that the spin lock is busy when trying to acquire the lock
In the form of busy waiting, the lock is constantly checked to see if it is available. When the task of the previous thread is not finished (locked),
The next thread will wait (without sleep), and when the previous thread completes, the next thread will execute immediately.
In a multi-CPU environment, using a spin lock instead of a common mutex can often improve performance for programs with short locks.
Exclusive locks:
When the previous thread’s task is not finished (locked), the next thread goes to sleep and waits for the task to complete.
When the previous thread completes the task, the next thread automatically wakes up and executes the task.
Conclusion:
Spin locks wait busy: When a locked resource is accessed, the caller thread does not sleep, but loops there until it is locked
Resource release lock.
Mutexes sleep: Sleep means that while accessing a locked resource, the caller thread sleeps so that the CPU can schedule other thread workers
Make it. Until the locked resource releases the lock. The dormant thread is awakened.
Pros and cons: The advantage of spinlocks is that because spinlocks do not cause callers to sleep, they do not perform time-consuming operations such as thread scheduling and CPU time slice rotation. So if the lock can be acquired in a very short time, spin locks are far more efficient than mutex locks.
The downside is that the spin lock takes up CPU all the time, and it keeps running without the lock — spin, so it takes up CPU if it doesn’t
The lock can be acquired in a very short time, which is definitely CPU inefficient. Spin locks do not make recursive calls.
-
* Spin locks: atomic, OSSpinLock, dispatch_semaphore_t
-
Mutexes: pthread_mutex, @synchronized, NSLock, NSConditionLock, NSCondition, NSRecursiveLock*
conclusion
The work is not easy, if you feel ok, please pay attention to it and give it a thumbs-up! ** as often in a variety of websites wandering porters, also collected a lot of iOS development information, interview information, also white whoring to free live links, created their own iOS development exchange circle, to want information can click to receive information