iOS Note _12_ multithreading

Source: Internet
Author: User

Main thread
    • After an iOS program runs, 1 threads are turned on by default, called the "main thread" or "UI thread" (Refreshing the UI interface is best done in the main thread, and there may be some inexplicable bugs in the child threads)
    • The role of the main thread
      • Display \ Refresh UI interface
      • Handling UI events (such as click events, scrolling events, drag events, etc.)
    • Watch out.
      • 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
    • Multi-threading implementations in iOS
      • Pthread (C language, programmer management)
        • A common set of multithreaded APIs
        • Suitable for unix\linux\windows and other systems
        • Cross-platform \ Portable
        • Very difficult to use
      • Nsthread (OC Language, programmer Management)
        • Use more object-oriented
        • Easy to use, direct manipulation of thread objects
      • GCD (c language, automatic management)
        • Designed to replace threading technology such as Nsthread
        • Make the most of your device's multicore
      • Nsoperation (OC language, automatic Management)
        • Based on gcd (bottom is GCD)
        • More simple and practical features than GCD.
        • Use more object-oriented
Nsthread
    • A Nsthread object represents a thread
    • Creating, starting Threads
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];[thread start];// 线程一启动,就会在线程thread中执行self的run方法
    • Common related usage
+ (NSThread// 获得主线程- (BOOL// 是否为主线程+ (BOOL// 是否为主线程// 获取当前线程NSThread *current = [NSThread currentThread];// 线程的名字- (void)setName:(NSString *)n;- (NSString *)name;
    • Other ways to create threads
      • Advantages: Simple and fast
      • Cons: Unable to set the thread in more detail
// 创建线程后自动启动线程[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];// 隐式创建并启动线程[self performSelectorInBackground:@selector(run) withObject:nil];
    • Controlling the state of a thread
// 启动线程- (void// 进入就绪状态 -> 运行状态。当线程任务执行完毕,自动进入死亡状态// 阻塞(暂停)线程+ (void)sleepUntilDate:(NSDate *)date;+ (void)sleepForTimeInterval:(NSTimeInterval)ti;// 进入阻塞状态// 强制停止线程+ (void)exit;// 进入死亡状态// 注意:一旦线程停止(死亡)了,就不能再次开启任务
Mutual exclusion Lock
    • Mutex use format
@synchronized(锁对象) {// 需要锁定的代码  }// 注意:锁定1份代码只用1把锁,用多把锁是无效的
Atomic and non-atomic properties
    • OC has nonatomic and atomic two choices when defining attributes
      • Atomic: Atomic attribute, locking for setter method (default is Atomic)
      • Nonatomic: Non-atomic attribute, does not lock the setter method
    • Comparison of Nonatomic and atomic
      • Atomic: Thread-safe, requires a lot of resources
      • Nonatomic: Non-thread-safe, suitable for small memory mobile devices
    • Recommendations for iOS development
      • All properties are declared as Nonatomic
      • Try to avoid multiple threads robbing the same piece of resources
      • As far as possible to locking, resource-grabbing business logic to the server-side processing, reduce the pressure of mobile clients
Inter-thread communication
    • What is called inter-thread communication
      • In 1 processes, threads often do not exist in isolation and require frequent communication between multiple threads
    • The embodiment of inter-thread communication
      • 1 Threads pass data to another 1 threads
      • After performing a specific task in 1 threads, go to another 1 thread to continue the task
    • Common methods for 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;
GCD
    • Nature and Benefits
      • Full name is the Grand Central Dispatch, which translates to the "Awesome Hub Scheduler"
      • GCD automatically manages the lifecycle of threads (creating threads, scheduling tasks, destroying threads)
      • programmers just need to tell gcd what they want to do and don't need to write any thread management code
    • steps to use GCD
      • customizing Tasks
        • Determine what you want to do
      • Add a task to the queue
        • gcd automatically takes the tasks in the queue and puts them in the corresponding thread to execute the
        • task out of the queue Fif O principle: FIFO, LIFO
    • functions common to perform Tasks
//perform tasks synchronously  dispatch_sync  (dispatch_queue_t  queue, Dispatch_ block_t block); //queue: Queue  //Block: Task  //Note: Using the Sync function to add tasks to the current serial queue will cause the current serial queue to be stuck. The synchronization mode blocks the current queue.  //perform tasks asynchronously  dispatch_async  (dispatch_queue_t  queue, dispatch_block_t block);d Ispatch_barrier_async (dispatch_queue_t  queue, dispatch_block_t block); //executes after the previous task execution, and the task behind it executes after it finishes executing the  //Note: This queue cannot be a global concurrent queue   
    • The difference between synchronous and asynchronous
      • Synchronization: Tasks can only be performed in the current thread, without the ability to open new threads
      • Async: Can perform tasks in a new thread, with the ability to open new threads
    • Types of queues
      • Concurrent queues (Concurrent Dispatch queue)
        • Multiple tasks can be executed concurrently (concurrently) (automatic opening of multiple threads concurrently executing tasks)
        • concurrency function is only valid under asynchronous (Dispatch_async) functions
      • Serial Queue (Serial Dispatch queue)
        • Let the task execute one after the other (once a task has finished executing, then the next task is performed)
    • Concurrent queues
//Create concurrent Queuesdispatch_queue_tQueue =Dispatch_queue_create ("queue name", dispatch_queue_concurrent)//First parameter const char *label queue name///second parameter dispatch_queue_attr_t attr queue type dispatch_queue_concurrent represents a concurrent queue//Get global concurrency queuedispatch_queue_tQueue =Dispatch_get_global_queue (Dispatch_queue_priority_default,0);//First parameter dispatch_queue_priority_t priority queue///second parameter unsigned long flags This parameter is temporarily useless, with a 0#defineDispatch_queue_priority_high2 //High#defineDispatch_queue_priority_default0 //Default (medium)#defineDispatch_queue_priority_low (-2)//Low#defineDispatch_queue_priority_background Int16_min//Backstage
    • Serial queue
// 创建串行队列(队列类型传递NULL或者DISPATCH_QUEUE_SERIAL)dispatch_queue_t queue = dispatch_queue_create("队列名称"NULL// 获得主队列,主队列也是串行队列dispatch_queue_t queue = dispatch_get_main_queue();
    • Inter-thread communication
0), ^{    // 执行耗时的异步操作...      dispatch_async(dispatch_get_main_queue(), ^{        // 回到主线程,执行UI刷新操作        });});
    • Deferred operation
      • There are 3 latency actions in iOS
        • Methods for calling NSObject
        • Using the GCD function
        • Using Nstimer
[self performSelector:@selector(run) withObject:nil afterDelay:2.02秒后再调用self的run方法dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{    2秒后执行这里的代码...});[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(test) userInfo:nil repeats:NO];
    • Disposable code
// 使用dispatch_once函数能保证某段代码在程序运行过程中只被执行1次staticdispatch_once_t onceToken;dispatch_once(&onceToken, ^{    // 只执行1次的代码(这里面默认是线程安全的)});
    • Fast Iteration
// 使用dispatch_apply函数能进行快速迭代遍历dispatch_apply(10, dispatch_get_global_queue(0, 0), ^(size_t index){    // 执行10次代码,index顺序不确定});
    • Queue Group
      • A requirement that can be met (but can also be implemented with dependent thread dependencies, as mentioned below)
        • First: Perform 2 time-consuming operations asynchronously, respectively
        • Second: Wait for 2 asynchronous operations to complete, then return to the main thread to perform the operation
dispatch_group_t group =  0), ^{    // 执行10), ^{    // 执行1个耗时的异步操作});dispatch_group_notify(group, dispatch_get_main_queue(), ^{    // 等前面的异步操作都执行完毕后,回到主线程...});
Single-Case mode
    • The role of the singleton pattern
      • You can guarantee that there is only one instance of a class when the program is running, and that the instance is easy for outside access
      • Thus conveniently control the number of instances, and save system resources
    • The use of single-case mode
      • Share a single resource throughout the application (this resource only needs to be initialized 1 times)
    • Implementation steps:
//Keep a global instance of static in. MStatic ID_instance;//Rewrite Allocwithzone: method, create a unique instance here (Note thread safety), the Alloc method calls Allocwithzone: Method+ (Instancetype) Allocwithzone: (struct_nszone *) zone{Static dispatch_once_tOncetoken;dispatch_once(&oncetoken, ^{_instance = [SuperAllocwithzone:zone]; });return_instance;}//provides 1 class methods for accessing unique instances from outside+ (Instancetype) sharedinstance{Static dispatch_once_tOncetoken;dispatch_once(&oncetoken, ^{_instance = [[ SelfALLOC] init]; });return_instance;}//Implement Copywithzone: Method- (ID) Copywithzone: (struct_nszone *) zone{return_instance;}
Nsoperation
    • Nsoperation and Nsoperationqueue steps to implement multithreading
      • Encapsulates the action that needs to be performed into a Nsoperation object
      • Then add the Nsoperation object to the Nsoperationqueue
      • The system will automatically remove the nsoperation from the Nsoperationqueue
      • Put the removed Nsoperation encapsulated operation into a new thread to execute
    • Nsoperation is an abstract class, there are 3 ways to use the Nsoperation subclass
      • Nsinvocationoperation
      • Nsblockoperation
      • Customizing subclass Inheritance Nsoperation, implementing the corresponding method internally
    • Nsinvocationoperation
// 创建NSInvocationOperation对象- (id)initWithTarget:(id)target selector:(SEL)sel object:(id)arg;// 调用start方法开始执行操作- (void)start;// 一旦执行操作,就会调用target的sel方法// 注意:默认情况下,调用了start方法后并不会开一条新线程去执行操作,而是在当前线程同步执行操作。只有将NSOperation放到一个NSOperationQueue中,才会异步执行操作
    • Nsblockoperation
// 创建NSBlockOperation对象+ (id)blockOperationWithBlock:(void (^)(void))block;// 通过addExecutionBlock:方法添加更多的操作- (void)addExecutionBlock:(void (^)(void))block;// 注意:只要NSBlockOperation封装的操作数 > 1,就会异步执行操作
    • Nsoperationqueue
// 添加操作到NSOperationQueue中- (void)addOperation:(NSOperation *)op;- (void)addOperationWithBlock:(void (^)(void))block;
    • Related actions
// 设置最大并发数- (NSInteger)maxConcurrentOperationCount;- (void)setMaxConcurrentOperationCount:(NSInteger)cnt;// 取消队列的所有操作- (void)cancelAllOperations;// 提示:也可以调用NSOperation的- (void)cancel方法取消单个操作// 暂停和恢复队列- (void)setSuspended:(BOOL// YES代表暂停队列,NO代表恢复队列- (BOOL)isSuspended;
    • Operation Dependent
      • Dependencies can be set between nsoperation to guarantee the order of execution
      • You can create a dependency between nsoperation of different queue
[operationB addDependency:operationA]; // 操作B依赖于操作A
    • Monitoring of operations
// 可以监听一个操作的执行完毕- (void (^)(void))completionBlock;- (void)setCompletionBlock:(void (^)(void))block;
    • Custom Nsoperation
      • Just rewrite-(void) The Main method, in which you implement the task you want to perform
      • Watch out.
        • 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
Calculate Time Difference
NSDate *start = [NSDate date];// 上下两句代码间放需要计算时间的程序NSDate *end = [NSDate date];NSLog(@"%f", [end timeIntervalSinceDate:start]);
begin = CFAbsoluteTimeGetCurrent();end = CFAbsoluteTimeGetCurrent();end - begin);
Summary:

1, in GCD, the method if the asynchronous function can open the sub-thread to do things, the method of the program will be executed in sequence, and then return to open the sub-thread to perform internal operations. If it is a synchronous function, then the child thread cannot be opened, and the synchronization function can only be executed one at a.
2, if the synchronization function is called in the main queue, it is easy to cause deadlock.

iOS Note _12_ multithreading

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.