iOS Multithreading Summary

Source: Internet
Author: User

1. Do not open too many threads simultaneously (no more than 5 threads) 2. Thread Concept 1> main thread: UI thread, display, refresh UI interface, handle UI control's event 2> child thread: Background thread, Asynchronous thread 3. Do not put the time-consuming operation on the main thread, to be placed in the sub-thread to execute one, Nsthread (Master) 1.3 Ways to create and start a thread 1> first, then start
// Create Object  //  start [thread start];

2> Create auto Start
[Nsthread detachnewthreadselector: @selector (Download:) totarget:self Withobject:nil];

3> Implicit creation (auto-start)
[Self performselectorinbackground: @selector (Download:) Withobject:nil];

2. Common method 1> get current thread
+ (Nsthread *) CurrentThread;

2> Get the main thread
+ (Nsthread *) Mainthread;

3> sleep (pause) thread
+ (void) Sleepuntildate: (NSDate *) date; + (void) Sleepfortimeinterval: (Nstimeinterval) ti;

4> set the name of the thread
-(void) SetName: (NSString *) n; -(NSString *) name;

Second, thread synchronization (Mastery) 1. Essence: To prevent multiple threads from robbing the same resource for data security issues 2. Implementation: Add a mutex to the code (synchronous lock)
@synchronized (self) {//  locked code }

Iii. GCD1. Queue and Task 1> tasks: What you need to do * encapsulate tasks with blocks 2> queues: Holding tasks * Global concurrent queues: Enables tasks to execute Dispatch_queue_priority_default priority concurrently
0);

* Create a serial queue yourself: Let the task execute one after the other
dispatch_queue_t queue = dispatch_queue_create ("cn.heima.queue_name", NULL);

* Home row: Let the task execute on the main thread
dispatch_queue_t queue = Dispatch_get_main_queue ();

2. Perform the task 1> synchronous execution: Do not have the ability to open a new thread dispatch_sync ... 2> Asynchronous execution: Ability to open new threads dispatch_async ... 3. Common combination (mastering) 1> Dispatch_async + global Concurrent Queue 2> Dispatch_async + self-created serial queue 4. Communication between threads (master)
0), ^{//  Execute time-consuming asynchronous Operation ...     ^ {//back to main thread, perform UI refresh Operation});   

All 5.GCD APIs are automatically imported into this library * primary header file in Libdispatch.dylib,xcode: #import <dispatch/dispatch.h> 6. Delay Execution (mastering) 1> perform .... After 3 seconds automatically returns to the current thread called Self's Download: method, and passes the parameter: @ "Http://xxx.jpg"
[Self performselector: @selector (Download:) Withobject:@ "http://xxx.jpg" Afterdelay:3];

2> Dispatch_after ...
// which queue the task is placed in to execute 0 ); Double 3 // delay How many seconds dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (Delay * nsec_per_sec)), queue, ^{ // tasks to be performed after 3 seconds });

7. Disposable code (Master)
Static dispatch_once_t oncetoken;dispatch_once (&oncetoken, ^{//  This code inside, in the process of running the program, will only execute 1 times });

Four, single-case mode (lazy-type) 1.ARC
@interfaceHmdatatool:nsobject+(instancetype) Shareddatatool;@end @implementationHmdatatool//used to save unique singleton objectsStatic ID_instace;+ (ID) Allocwithzone: (struct_nszone *) zone{Staticdispatch_once_t oncetoken;dispatch_once (&oncetoken, ^{_instace=[Super Allocwithzone:zone];});return_instace;} +(instancetype) shareddatatool{Staticdispatch_once_t oncetoken;dispatch_once (&oncetoken, ^{_instace=[[Self alloc] init];});return_instace;} - (ID) Copywithzone: (Nszone *) zone{return_instace;}@end

2. Non-arc
@interfaceHmdatatool:nsobject+(instancetype) Shareddatatool;@end @implementationHmdatatool//used to save unique singleton objectsStatic ID_instace;+ (ID) Allocwithzone: (struct_nszone *) zone{Staticdispatch_once_t oncetoken;dispatch_once (&oncetoken, ^{_instace=[Super Allocwithzone:zone];});return_instace;} +(instancetype) shareddatatool{Staticdispatch_once_t oncetoken;dispatch_once (&oncetoken, ^{_instace=[[Self alloc] init];});return_instace;} - (ID) Copywithzone: (Nszone *) zone{return_instace;} -(OneWayvoid) Release {}- (ID) Retain {returnSelf ;} -(Nsuinteger) retaincount {return 1;} - (ID) Autorelease {returnSelf ;}@end

V. Nsoperation and NSOperationQueue1. Type of queue 1> home column
[Nsoperationqueue Mainqueue];

* Actions added to the "home column" will be placed in the main thread to execute

2> Non-Home row
[[Nsoperationqueue alloc] init]

* Actions added to the "non-Home column" will be placed in the child thread execution

2. Queue Add Task
-(void) Addoperation: (Nsoperation *) op; -(void) Addoperationwithblock: (void (^) (void)) block;

3. Common usage 1> Setting the maximum number of concurrent
- (Nsinteger) maxconcurrentoperationcount; -(void) Setmaxconcurrentoperationcount: (Nsinteger) CNT;

2> Other operations of the queue * Cancel all operations
-(void) cancelalloperations;

* Pause All operations
[Queue Setsuspended:yes];

* Restore all operations
[Queue Setsuspended:no];

4. Dependencies between actions (interview questions) * Nsoperation can be set to ensure the order of execution
[Operationb Adddependency:operationa];

Operation B relies on operation A, and after operation a finishes, the operation is performed b* Note: You cannot rely on each other, such as a dependent b,b dependency A * can create a dependency between nsoperation of different queue 5. Communication between threads
Nsoperationqueue *queue = [[Nsoperationqueue alloc] init];[ Queue Addoperationwithblock:^{}];

1. Perform some more time-consuming operations//2. Back to the main thread
[[Nsoperationqueue Mainqueue] addoperationwithblock:^{     };}];

Six, the way from the other thread back to the main thread 1.perform ...
1 [self performselectoronmainthread:<# (SEL) #> withobject:<# (ID) #> waituntildone:< # (BOOL) #>];

2.GCD
Dispatch_async (Dispatch_get_main_queue (), ^{});

3.NSOperationQueue
[[Nsoperationqueue Mainqueue] addoperationwithblock:^{}];

It is important to note that you should not use GCD synchronization with the home team, otherwise there will be problems, such as this usage is wrong

iOS Multithreading Summary

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.