Multithreading
1. The principle of multithreading
1> At the same time, the CPU can only handle 1 threads, and only 1 threads are working (executing)
2> multi-threaded concurrency (simultaneous) execution, in fact, the CPU is quickly dispatched between multiple threads (switching)
3> If the CPU schedules threads fast enough, it creates the illusion of multi-threaded concurrency execution
If the thread is very, very many, it will happen:
1>. CPU will be dispatched between N multithreading, the CPU will be exhausted, consumes a lot of CPU resources
2> the frequency at which each thread is scheduled to execute is reduced (the execution efficiency of the thread is reduced)
2. Advantages and disadvantages of multithreading
1>. Advantages of multithreading
To improve the execution efficiency of the program appropriately
Can appropriately improve resource utilization (CPU, memory utilization)
2>: Disadvantages of multithreading
Open threads need to occupy a certain amount of memory (by default, the main thread takes up 1M, the child threads occupy 512KB), if you open a large number of threads, will consume a lot of memory space, reduce the performance of the program
The more threads, the greater the overhead of the CPU on the dispatch thread
Programming is more complex: such as communication between threads, multi-threaded data sharing
3. Main thread
After an iOS program runs, 1 threads are turned on by default, called the "main thread" or "UI thread"
1> main thread function
Display \ Refresh UI interface
Handling UI events (such as click events, scrolling events, drag events, etc.)
2>. Using the main thread note
Do not put more time-consuming operations into the main thread
Time-consuming operations can get stuck in the main thread, seriously affecting the smoothness of the UI, giving users a "card" bad experience
4.NSThread
Several ways to 1> the thread
* First created, then started
Nsthread *thread = [[Nsthread alloc] initwithtarget:self selector: @selector (run) Object:nil];
[Thread start];
* Direct Start
A>. [Nsthread detachnewthreadselector: @selector (Run) totarget:self Withobject:nil];
B>. [Self Performselectorinbackground: @selector (Run) Withobject:nil];
2> Other uses
Nsthread *current = [Nsthread CurrentThread]; Gets the current thread
+ (Nsthread *) Mainthread; Get the main thread
+ (void) exit; Force Stop Thread
* Blocking (pausing) threads
+ (void) Sleepuntildate: (NSDate *) date;
+ (void) Sleepfortimeinterval: (Nstimeinterval) ti;
3> Sync Lock (Mutual exclusion lock)
1 blocks of resources may be shared by multiple threads, that is, multiple threads may access the same piece of resources, such as multiple threads accessing the same object, the same variable, the same file, and when multiple threads access the same resource, it can easily cause data confusion and data security problems
The use of synchronous locks: Multiple threads rob the same piece of resources
A>. Synchronization lock Use Format
@synchronized (Lock Object) {//code to be locked}
Note: Locking 1 parts of code with only 1 locks, with multiple locks is not valid
B> advantages and disadvantages of synchronous locks
Advantages: It can effectively prevent the data security problem caused by multi-thread snatch resource
Cons: Consumes a lot of CPU resources
C> thread synchronization
Thread synchronization means that multiple threads perform tasks sequentially
Synchronous lock is the use of thread synchronization technology
4> Inter-thread communication
-(void) Performselectoronmainthread: (SEL) Aselector withobject: (ID) arg waituntildone: (BOOL) wait;
-(void) Performselector: (SEL) aselector onthread: (Nsthread *) THR Withobject: (ID) arg waituntildone: (BOOL) wait;
2.GCD (Focus)
Advantages of 1> GCD
GCD is Apple's solution for multi-core parallel computing
GCD will automatically take advantage of more CPU cores (such as dual-core, quad-core)
GCD automatically manages the life cycle of threads (create threads, schedule tasks, destroy threads)
Programmers just need to tell gcd what tasks they want to perform, without having to write any thread management code
2> Types of queues
* Concurrent Queue
Get a global concurrent queue: Dispatch_get_global_queue
* Serial Queue
A. Create yourself: dispatch_queue_create
B. Home row: Dispatch_get_main_queue
Concurrency and serialization determine how tasks are executed
Concurrency: Multiple tasks concurrently (concurrently) executed
Serial: Once a task is completed, the next task is performed
3> method types for performing tasks
* Synchronization (Sync) execution
* Asynchronous (Async) execution
Synchronous and asynchronous determine whether to open a new thread
Synchronous: Performs a task in the current thread without the ability to open a new thread
Async: Perform a task in a new thread with the ability to open a new thread
4> Inter-thread communication
Dispatch_async (
Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{
Perform time-consuming asynchronous operations ...
Dispatch_async (Dispatch_get_main_queue (), ^{
Go back to the main thread and perform a UI refresh operation
});
});
5> Other uses
Dispatch_once//For Singleton objects
Dispatch_after//Delay Loading
Dispatch_group_async\dispatch_group_notify//Queue Group
3.NSOperation
1> Basic Use
A>. Nsinvocationoperation:-(ID) Initwithtarget: (ID) Target selector: (SEL) SEL object: (ID) arg;
B>. Nsblockoperation: + (ID) Blockoperationwithblock: (void (^) (void)) block;
-(void) Addexecutionblock: (void (^) (void)) block; Add action
Operations are performed asynchronously as long as the nsblockoperation encapsulated operand > 1
2> Nsoperationqueue (Key)
* Add action to Nsoperationqueue
-(void) Addoperation: (Nsoperation *) op;
-(void) Addoperationwithblock: (void (^) (void)) block;
* Maximum number of concurrent settings
-(Nsinteger) Maxconcurrentoperationcount;
-(void) Setmaxconcurrentoperationcount: (Nsinteger) CNT;
* Cancel all operations of the queue
-(void) cancelalloperations;
Tip: You can also call the Nsoperation-(void) Cancel method to cancel a single operation
* Pause and Resume queue
-(void) setsuspended: (BOOL) b; Yes means pause queue, no for recovery queue
-(BOOL) issuspended;
* Set Dependencies (interview questions)
[Operationb Adddependency:operationa]; Action B depends on action a
3> Customizing operation (understanding Basic processes)
Rewrite-(void) The Main method, where you implement the task you want to perform
overriding-(void) The note point of the Main method
Create an auto-free pool yourself (because if it is an asynchronous operation, you cannot access the main thread's auto-free pool)
Often pass-(BOOL) IsCancelled method detects if the operation is canceled and responds to cancellation
4> How to resolve a picture (a URL) Repeat download question (interview question)
Use a dictionary or an object to save the downloaded asynchronous operation based on a URL to determine if the asynchronous operation exists and is not created