IOS multithreading summary, ios Multithreading
1. Do not open too many threads at the same time (1 ~ 3 threads, no more than 5) 2. thread Concept 1> main thread: UI thread, display and refresh UI interface, process UI control events 2> sub-thread: Background thread, asynchronous thread 3. do not place time-consuming operations in the main thread, but execute 1. NSThread (master) 1. three ways to create and start a thread: 1> Create a thread first, 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 performSelectorInBackground:@selector(download:) withObject:nil];
2. Common method 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;
Ii. Thread Synchronization (master) 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}
3. GCD1. queue and Task 1> tasks: What operations are required * use blocks to encapsulate tasks 2> queue: stores tasks * Global concurrent Queues: allows tasks to concurrently execute DISPATCH_QUEUE_PRIORITY_DEFAULT priority
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_name", NULL);
* Main queue: run the task in the main thread.
dispatch_queue_t queue = dispatch_get_main_queue();
2. function 1> synchronous execution: dispatch_sync is not capable of enabling new threads... 2> asynchronous execution: capable of enabling new threads. dispatch_async... 3. common combinations (master) 1> dispatch_async + global concurrent queue 2> dispatch_async + self-created serial queue 4. inter-thread communication (master)
Dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {// execute time-consuming asynchronous operations... dispatch_async (dispatch_get_main_queue (), ^ {// return to the main thread and execute the UI refresh operation });});
5. all APIs of GCD are in libdispatch. dylib, Xcode will automatically import this library * main header file: # import <dispatch/dispatch. h> 6. delayed execution (master) 1> perform .... // automatically return to the current thread after 3 seconds to call self's download: method, and pass the parameter: @ "http://xxx.jpg"
[self performSelector:@selector(download:) withObject:@"http://xxx.jpg" afterDelay:3];
2> dispatch_after...
// The queue in which the task is put to execute dispatch_queue_t queue = queue (latency, 0); double delay = 3; // The number of seconds delayed dispatch_after (dispatch_time (DISPATCH_TIME_NOW, (int64_t) (delay * NSEC_PER_SEC), queue, ^ {// task to be executed in 3 seconds });
7. One-time code (master)
Static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {// The code above will always be executed once during the program running });
Iv. Singleton mode (lazy) 1.ARC
@ Interface HMDataTool ool: NSObject + (instancetype) sharedDataTool OOl; @ end @ implementation HMDataTool ool // used to save the 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 ool {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {_ instace = [[self alloc] init] ;}); return _ instace ;}- (id) copyWithZone :( NSZone *) zone {return _ instace;} @ end
2. Non-ARC
@ Interface HMDataTool ool: NSObject + (instancetype) sharedDataTool OOl; @ end @ implementation HMDataTool ool // used to save the 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 ool {static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {_ instace = [[self alloc] init] ;}); return _ instace ;}- (id) copyWithZone :( NSZone *) zone {return _ instace;}-(oneway void) release {}-(id) retain {return self;}-(NSUInteger) retainCount {return 1 ;} -(id) autorelease {return self;} @ end
5. NSOperation and NSOperationQueue1. queue type 1> main queue Column
[NSOperationQueue mainQueue];
* Operations added to the "main queue" 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.
2. Add a task to the queue
- (void)addOperation:(NSOperation *)op;- (void)addOperationWithBlock:(void (^)(void))block;
3. 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 setSuspended:YES];
* Restore all operations
[queue setSuspended:NO];
4. dependencies between operations (interview questions) * dependencies can be set between NSOperation to ensure the execution order
[operationB addDependency:operationA];
// Operation B depends on Operation A. Operation B is executed only after operation A is executed. * Note: operations A depends on B, for example, B depends on A * You can create dependencies between NSOperation of different queue. 5. communication between threads
NSOperationQueue *queue = [[NSOperationQueue alloc] init];[queue addOperationWithBlock:^{}];
// 1. Execute some time-consuming operations // 2. Return to the main thread
[[NSOperationQueue mainQueue] addOperationWithBlock:^{ }]; }];
6. Return from other threads 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:^{ }];
Additionally, you must note that you should not use it with the main queue when using GCD synchronization. Otherwise, problems may occur. For example, this usage is incorrect.