Comprehensive parsing of multithreading in iOS development

Source: Internet
Author: User

Comprehensive parsing of multithreading in iOS development

 

I. Basic concepts of Multithreading

1. Process
A process is an application running in the system. Each process is independent, and each process runs in its dedicated and protected memory space.

2. threads
Basic Concepts
To execute a task, a process must have a thread (each process must have at least one thread). A thread is the basic execution unit of a process and a process (Program) all tasks are executed in the thread.

Thread serial
Task execution in one thread is serialized. If you want to execute multiple tasks in one thread, you can only execute these tasks one by one in sequence. That is to say, at the same time, one thread can only execute one task.

3. Multithreading
Basic Concepts
That is, multiple threads can be enabled in one process, and each thread can execute different tasks in parallel (at the same time ).

Parallel thread
Parallel Execution. For example, you can enable three threads to download three files (File A, file B, and file C.

Principle of multi-thread concurrent execution
At the same time, the CPU can only process one thread, and only one thread is running ). Multi-thread concurrent (concurrent) execution is actually the process where the CPU schedules (switches) between multiple threads quickly. If the CPU schedules the thread fast enough, it creates the illusion of multi-thread concurrent execution.

4. Advantages and Disadvantages of Multithreading
Advantages
1) The program execution efficiency can be appropriately improved.
2) appropriately improving resource utilization (CPU and memory usage)
Disadvantages
1) enabling a thread requires a certain amount of memory space (by default, the main thread occupies 1 MB, and the sub-thread occupies KB). If a large number of threads are enabled, a large amount of memory space will be occupied, reduces Program performance.
2) The more threads, the higher the CPU overhead on the scheduling thread.
3) more complex program design: for example, inter-thread communication and multi-thread data sharing

5. Notes:
(1) do not open too many threads at the same time (1 ~ 3 threads, no more than 5 threads)
(2) main thread: UI thread, display and refresh the UI interface, and process UI control events
(3) subthread: Background thread, asynchronous thread
(4) do not place time-consuming operations in the main thread, but execute them in the Child thread.

Ii. NSThread

1. Three ways to create and start a thread
(1) first create and then start

// Create
NSThread * thread = [[NSThread alloc] initWithTarget: self
Selector: @ selector (download :) object: nil];
// Start [thread start];

(2) automatic start after creation

[NSThread detachNewThreadSelector: @ selector (download :) toTarget: self
WithObject: nil];

(3) Implicit creation (Automatic startup)

[Self defined mselectorinbackground: @ selector (download :)
WithObject: nil];

2. Common Methods
(1) obtain the current thread

+ (NSThread *)currentThread;

(2) obtain the main thread
+ (NSThread *)mainThread;

(3) sleep (paused) thread

+ (Void) sleepUntilDate :( NSDate *) date;
+ (Void) sleepForTimeInterval :( NSTimeInterval) ti;

(4) set the thread name

-(Void) setName :( NSString *) n;
-(NSString *) name;

Thread Synchronization
1. essence: to prevent data security problems caused by multiple threads grabbing the same resource

2. Implementation: Add a mutex lock (synchronization lock) to the code)
@ Synchronized (self ){
// Locked code
}

Iii. GCD

1. queue and task
(1) task: What operations do you need to perform?
Use block to encapsulate tasks

(2) queue: stores tasks
Global concurrent queue: Allows concurrent task execution

Dispatch_queue_t queue =
Dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 );

Self-created serial queue: Let the task be executed one by one

Dispatch_queue_t queue = dispatch_queue_create ("cn. heima. queue ",
NULL );

Main queue: Let the task be executed in the main thread

Dispatch_queue_t queue = dispatch_get_main_queue ();

2. Function for executing the task
(1) Synchronous execution: not capable of enabling new threads
Dispatch_sync...

(2) asynchronous execution: capable of enabling new threads
Dispatch_async...

3. Common combinations

(1) asynchronous Function + concurrent queue: enable multiple threads and execute tasks concurrently
(2) asynchronous functions + Serial queue: Enable a thread to execute tasks in a serial mode.
(3) Synchronous functions + concurrent Queues: threads are not enabled and tasks are executed in serial mode.
(4) Synchronous Function + Serial queue: execute tasks in a serial mode without threads
(5) asynchronous functions + main queue columns: tasks are executed serially in the main thread without threads.
(6) Synchronous functions + main queue columns: threads are not enabled and tasks are executed serially (note the occurrence of deadlocks)
(7) Pay attention to the differences in the execution sequence between synchronous and asynchronous Functions

Note:When a synchronization function adds a task to the current serial queue, the current thread is stuck and a deadlock occurs.

4. Inter-thread Communication <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Expires + expires + CgkJPHA + expires/expires + Cgk8L2Jsb2NrcXVvdGU + expires + PGJyIC8 + expires/expires + CjxwcmUgY2xhc3M9 "brush: java;"> [self performSelector:@selector(download:) withObject:@http://555.jpg afterDelay:3];

<2> dispatch_after

// The queue in which the task is put to execute dispatch_queue_t queue =
Dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); double
Delay = 3;
Dispatch_after (dispatch_time (DISPATCH_TIME_NOW,
(Int64_t) (delay * NSEC_PER_SEC), queue, ^ {
// Task to be executed 3 seconds later
});

(2) One-time code

Static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {
// The code above will always be executed once when the program is running });

(3) fence function (control the execution sequence of tasks)

dispatch_barrier_async(queue, ^{    NSLog(@--dispatch_barrier_async-);});

(4) Fast iteration (enabling multiple threads to complete iterative operations concurrently)

Dispatch_apply (subpaths. count, queue, ^ (size_t index ){
});

(5) queue group (same fence function)

// Create a queue Group
Dispatch_group_t group = dispatch_group_create ();
// After the tasks in the queue group are completed, execute this function.
Dispatch_group_notify (dispatch_group_t group,
Dispatch_queue_t queue,
Dispatch_block_t block );

Iv. NSOperation and NSOperationQueue

1. Basic concepts:
NSOperation is the packaging of GCD. It has two core concepts: queue + operation]
2. Basic use
(1) NSOperation is an abstract class and can only be a subclass of NSOperation.
(2) The three sub-classes are NSBlockOperation, NSInvocationOperation, and NSOperation class.
(3) Use NSOperation and NSOperationQueue in combination to implement multi-thread concurrency

3. Queue type
(1) Main Columns

[NSOperationQueue mainQueue] operations added to the main queue column will be executed in the main thread

(2) Non-main Columns

[[NSOperationQueue alloc] init] operations added to the non-main queue column will be executed in the Child thread

4. Add a task to the queue

-(Void) addOperation :( NSOperation *) op;

-(Void) addOperationWithBlock :( void (^) (void) block;

5. Common usage
(1) set the maximum number of concurrent jobs

- (NSInteger)maxConcurrentOperationCount;- (void)setMaxConcurrentOperationCount:(NSInteger)cnt;

(2) Other queue operations

Cancel all operations
-(Void) cancelAllOperations;

Pause all operations
[Queue setsuincluded: YES];

Restore all operations
[Queue setsuincluded: NO];

6. dependencies between operations (interview questions)

Dependencies can be set between NSOperation to ensure the execution sequence [operationB addDependency: operationA];
// Operation B depends on Operation A. Operation B is executed only after operation A is executed. Note: Operations B cannot depend on each other. For example, operation A depends on Operation B, B Depends on A. dependencies can be created between NSOperation of different queue.

7. Communication between threads

NSOperationQueue * queue = [[NSOperationQueue alloc] init]; [queue
AddOperationWithBlock: ^ {
// 1. Perform some time-consuming operations
// 2. Return to the main thread
[[NSOperationQueue mainQueue] addOperationWithBlock: ^ {
}];
}];

V. Singleton Mode

1. idea of implementing the singleton mode of ARC
(1) provide a static global variable inside the class.
(2) provide a class method to facilitate external access
(3) rewrite the + allocWithZone method to ensure that the memory space is always allocated only once for the single-instance object
(4) For rigor, rewrite the-copyWithZone method and the-MutableCopyWithZone method.

(1) create a class factory Method

@ Interface DataTool ool: NSObject
+ (Instancetype) sharedDataTool OOl; @ end

@ Implementation DataTool ool

// Used to save a unique singleton object
Static id _ instace;
// Override the allocWithZone Method
+ (Id) allocWithZone :( struct _ NSZone *) zone {
Static dispatch_once_t onceToken;
Dispatch_once (& onceToken, ^ {
_ Instace = [super allocWithZone: zone];
});
Return _ instace ;}

// Implementation of the sharedDataTool ool method + (instancetype) sharedDataTool ool {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {_ instace = [[self alloc] init];}); return _ instace ;}
// Override the copyWithZone method-(id) copyWithZone :( NSZone *) zone {return _ instace;} @ end

2. How MRC implements Singleton
(1) provide a static global variable inside the class.
(2) provide a class method to facilitate external access
(3) rewrite the + allocWithZone method to ensure that the memory space is always allocated only once for the single-instance object
(4) For rigor, rewrite the-copyWithZone method and the-MutableCopyWithZone method.
(5) rewrite the release method
(6) rewrite the retain Method
(7) we recommend that you return a maximum value in the retainCount method.

// Declare a class factory method @ interface ool: NSObject + (instancetype) sharedDataTool OOl; @ end

@ Implementation HMDataTool ool

// Used to save a unique singleton object
Static id _ instace;
+ (Id) allocWithZone :( struct _ NSZone *) zone {
Static dispatch_once_t onceToken;
Dispatch_once (& onceToken, ^ {
_ Instace = [super allocWithZone: zone];
});
Return _ instace ;}

 + (instancetype)sharedDataTool{    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        _instace = [[self alloc] init];    });    return _instace;}

// Rewrite the copyWithZone method.
-(Id) copyWithZone :( NSZone *) zone {
Return _ instace ;}

// Override release-(oneway void) release {}
// Override retain-(id) retain {return self ;}
- (NSUInteger)retainCount {    return MAXFLOAT;}
// Override autorelease-(id) autorelease {return self;} @ end

3. Determine the compiler environment: ARC or MRC Method

# If _ has_feature (objc_arc) // The current compiler environment is ARC # else // The current compiler environment is MRC # endif
6. Returning from other threads to the main thread

1. performselecdomainmainthread

[self performSelectorOnMainThread:<#(SEL)#> withObject:<#(id)#> waitUntilDone:<#(BOOL)#>];

2. GCD

dispatch_async(dispatch_get_main_queue(), ^{});

3. NSOperationQueue

[[NSOperationQueue mainQueue] addOperationWithBlock:^{}];
VII. class initialization method

1. + (void) load

When a class is loaded to the OC runtime system (memory) for the first time, the program will be called once it is started, and the program will only be called once.

2. + (void) initialize

When a class is used for the first time (for example, a method of the class is called), it is called not once the program starts.

3. running the program: An operation in one class only needs to be executed once. Put this operation in the + (void) load method, which is the most suitable

8. cell Image download

1. Interview Questions
1> how to prevent repeated downloads of images corresponding to a url

"Cell image download ideas-sandbox Caching"

2> what is the default cache duration of SDWebImage?

1 week

3> How is SDWebImage implemented at the underlying layer?

(1) No sandbox Cache
Steps:
1. cache the required image first
2. Retrieve the image from the image according to the image url and display the image directly to the cell.
3. The image does not exist. A placeholder image is displayed.
4. Check whether operations contains download operations based on the image url.
5. If the download operation exists, the task is being downloaded.
6. the download operation does not exist. Put it in operation.
7. After the download is complete, remove the operation from operation and put the image into the image.
8. Refresh the table

(2) sandbox caching
1. Retrieve the image from the image according to the image URL and display it to the cell.
2. If the image does not exist, check whether any image in the sandbox is displayed on the cell.
3. If a placeholder image does not exist
4. Check whether operation downloads exist based on the image URL.
5. If the creation and download operations do not exist, put them in operation.
6. After the download is complete, remove the operation from operation.
7. Refresh the table by row
8. Save the image to the sandbox.

2. Use of the third-party framework SDWebImage
(1) Common Methods

-(Void) sd_setImageWithURL :( NSURL) Url placeholderImage :( UIImage) Placeholder;

- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options;
-(void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;

-(Void) sd_setImageWithURL :( NSURL) Url placeholderImage :( UIImage) Placeholder options :( SDWebImageOptions) options progress :( SDWebImageDownloaderProgressBlock) progressBlock
Completed :( SDWebImageCompletionBlock) completedBlock;

(2) Memory Processing: When the app receives a memory warning
// When the app receives a memory warning

-(Void) applicationDidReceiveMemoryWarning :( UIApplication *) application {
SDWebImageManager * mgr = [SDWebImageManager sharedManager];
// 1. Cancel the download operation
[Mgr cancelAll];
// 2. Clear the memory cache
[Mgr. imageCache clearMemory];}

(3) SDWebImageOptions

SDWebImageRetryFailed: After the download fails, SDWebImageLowPriority will be automatically downloaded again: When UI interaction is ongoing, some internal download operations SDWebImageRetryFailed will be automatically suspended | SDWebImageLowPriority: has the above two functions

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.