Knowledge points
1. Understanding the concept of threading
Use of 2.NSThread
Use of 3.NSOperation
Use of 4.GCD
5. Wire lock, Thread safe
===============================
1. Multithreading is a multi-tasking implementation of the technology, allowing multiple tasks simultaneously, can more reasonable use of CPU resources, improve efficiency, prevent user interface lag.
In iOS, all UI processing is done only on the main thread.
What is a process?
• A simple process is a single application running on our computer, each of which is a process, and each process is independent, and each process runs within its dedicated protected memory space (the window system can be viewed through the Task Manager, The Mac system can be viewed through the activity monitor)
What is a thread?
• Through the above introduction we know what is the process, then how to let the process run, this time will be wired, that is, every application wants to run, at least one thread exists, in fact, when the application starts, our system will default to help our application to open a thread, This thread is also called the ' main thread ', or ' UI thread '
the relationship between the process and the thread
• The thread is the execution unit in progress, and all the tasks of the process are executed inline, for example: a process is like a department in a company, a thread represents a colleague in a department, and the main thread of course is our boss, a company can not have a boss, a program can not without thread is actually a truth.
What is a CPU?
· The CPU (central processing Unit) is an ultra-large-scale integrated circuit, as long as it is used to interpret computer instructions and to process data in computer software. Processing
Multi-Threading Principle
• At the same time, the CPU value can handle a thread, only one thread is executing, multithreading refers to the simultaneous execution of multiple threads, in fact, the CPU is fast switching between multiple threads, if the CPU scheduler thread fast enough, Then it will create the illusion of multi-threading concurrency execution, and when the thread is particularly large, then the efficiency of the CPU in multiple switches will be reduced, while consuming a lot of CPU resources, the execution efficiency of the thread will be reduced.
Multithreading Benefits
• Can improve the execution efficiency of the program appropriately
• Increase the utilization of resources appropriately
Multithreading disadvantages
• Open threads require a certain amount of memory space, and if you open a large number of threads, it can consume a lot of memory and reduce the performance of the program
• threading The more the CPU on the scheduling thread overhead, the program is more complex design, it is not recommended to open too many threads, generally open 2~5 bar for the best (and use and cherish);
Main thread
• When the application starts, the default thread that the system creates for us is called the ' main thread ' or ' UI thread ';
• The main thread is typically used to display or refresh the UI interface such as: Click, scroll, drag and drop events
===============================
2.NSThread Line Program Control system
1). Create a thread and automate
[Nsthread detachnewthreadselector: @selector (dosomething) totarget:self Withobject:nil];
2).创建线程,不自动执行 [[NSThread alloc] initWithTarget:self selector:@selector(doSomeThing) object:nil];3).设置线程名 thread.name = @"另一个线程";4).执行线程 [thread start];5).线程取消 [thread cancel];6).函数内获取当前线程 [NSThread currentThread];7).获取主线程 [NSThread mainThread];7).线程休眠 [NSThread sleepForTimeInterval:1.0f]; // 休眠几秒 [NSThread sleepUntilDate:date]; // 休眠到指定时间8).线程退出 [NSThread exit];9).线程通信 [self performSelector:@selector(function) onThread:[NSThread mainThread] withObject:nil waitUntilDone:YES];
===============================
3.NSOperation, a task-centric multithreading technology that does not directly manage threads
1). Nsoperation is an abstract parent class that should not be used directly, but should use its subclasses
Nsinvocationoperation
[[Nsinvocationoperation alloc] initwithtarget:self selector: @selector (dosomething) Object:nil];
NSBlockOperation [NSBlockOperation blockOperationWithBlock:^{}]; 添加任务间的依赖关系,前者依赖于后者的完成,也就是后者执行完,前者才能执行,依赖关系需要放在添加到队列之前设置 [invocation addDependency:blockOperation]; 如果有必要,可以让Operation取消 [invocation cancel];2.NSOperationQueue,任务队列,NSOperation对象需要添加到队列里面才会执行 添加到队列里之后,自动会给每个NSOperation对象创建一个线程去执行 创建NSOperationQueue [[NSOperationQueue alloc] init]; 设置最大并发数 queue.maxConcurrentOperationCount = 1; 添加任务到队列里 [queue addOperation:blockOperation]; 让队列里面,所有的Operation都取消 [queue cancelAllOperations]; 获取当前线程对列 currentQueue 获取主线程对列 mainQueue
===============================
4.GCD is a set of C language Thread control API, is the nsoperation implementation of the bottom, with block to represent a task
1). Create a queue
Dispatch_queue_create ("QF queue", dispatch_queue_concurrent);
2).系统的队列 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // 全局队列 dispatch_get_main_queue(); // 主线程队列3).异步执行任务 dispatch_async(globalQuque, ^{});4).创建分组 dispatch_group_create();5).添加任务到分组,并执行 dispatch_group_async(group, globalQuque, ^{});6).分组执行完的通知 dispatch_group_notify(group, mainQuque, ^{});
===============================
5. Thread Lock
1). Mode 1:
_lock = [[Nslock alloc] init];
[_lock tryLock];[_lock unlock];2).方式2: @synchronized(self) {}
Nsthread
//多线程 -- 为了将一些耗时的操作放在多线程中去执行 主要是为了给一个好的用户体验,防止卡顿的效果//越多越好? 消耗内存和cpu的使用效率//创建多线程的方式//1.NSThread//2.CGD//3.NSOperation//程序运行的时候,会默认创建一个线程,这个线程称之为主线程/UI线程,所有的UI相关的操作都需要在这个线程中执行BOOL res1 = [NSThread isMainThread]; //判断是否是子线程BOOL RES2 = [NSThread isMultiThreaded]; //判断是否是多线程
1. Create thread Subtraction method creation
Operations – Functions – Several lines of code – functions – Tasks
Nsthread * Thread1 = [[Nsthread alloc] initwithtarget:self selector: @selector (ThreadRun) Object:nil];
The third argument: object is passed using object if the second argument selector with a parameter
The newly created thread is called a child thread or a task thread/background thread
//线程的名字thread1.name = @"子线程1";//线程的优先级(double) 0 - 1thread1.threadPriority = 0.5;//设置线程的优先级(枚举值)需要在线程开启前设置 否则无效。thread1.qualityOfService = NSQualityOfServiceBackground;//2.开启线程[thread1 start];
Create line loads method create and execute thread
[Nsthread detachnewthreadselector: @selector (ThreadRun) totarget:self Withobject:nil];
Cannot set the name of the thread can go to the method through the CurrentThread method to get the thread and then the assignment operation
NSObject method to create a thread
[Self Performselectorinbackground: @selector (ThreadRun) Withobject:nil];
GCD
GCD-A set of C-based API interfaces that add blocks as tasks to the queue for operation
//GCD 优点:可以控制多个线程的执行顺序 这个功能是NSThread不具有的 //缺点: 不能取消线程//GCD 语法都是c语言函数//1.创建队列dispatch_queue_t queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL);//queue 队列/线程池//dispatch 调度/执行//第一个参数 队列的名字 通常写nil//第二个参数 串行/并行//DISPATCH_QUEUE_SERIAL 串行 按顺序执行队列里的线程//DISPATCH_QUEUE_CONCURRENT 并行 同时执行若干个线程
Exit of the listener thread
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(threadOut) name:NSThreadWillExitNotification object:nil];//NSThreadWillExitNotification 线程退出的频道//只需要监听这个频道 当线程退出的时候 就会收到通知/消息 然后调用响应的方法//取消线程 cancel并不能把一个线程退出 调用cancle方法只是为了告诉当前线程的isCancelled属性为YES 并且触发监听[thread cancel];if (thread.isCancelled) { //如果为YES 退出线程 也可以使用return [NSThread exit];}//threadRun这个方法是我们子线程的入口函数 - 当这个方法执行完毕的时候,线程就已经是死亡状态了
Timer
//GCD定时器//1.创建定时器//需要把定时器定义成全局变量 否则会被立刻释放self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());//2.设置定时器 第一个参数为时间间隔 第二个参数次数dispatch_source_set_timer(self.timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);//3.定时器定时的操作dispatch_source_set_event_handler(self.timer, ^{ //定时器每隔几秒钟要做的操作 NSLog(@"d");});//执行定时器dispatch_resume(self.timer);
Delay operation
[NSThread sleepForTimeInterval:2.0];[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:10]];-(void)createQueue2{ NSLog(@"将要延时..."); //延时几秒操作 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ //DISPATCH_TIME_NOW 从现在开始 //NSEC_PER_SEC 代表的是秒 //延时几秒之后的操作 NSLog(@"延时执行"); }); [self performSelector:@selector(afterRun) withObject:nil afterDelay:2.0]; [NSObject cancelPreviousPerformRequestsWithTarget:self];}
Thread Group
//线程组 监听线程dispatch_group_t group = dispatch_group_create();//创建全局队列dispatch_queue_t queue = dispatch_get_global_queue(0, 0);dispatch_group_async(group, queue, ^{ [NSThread sleepForTimeInterval:2.0]; NSLog(@"线程1执行完毕");});dispatch_group_async(group, queue, ^{ [NSThread sleepForTimeInterval:3.0]; NSLog(@"线程2执行完毕");});//前两个线程结束后会通知这个线程dispatch_group_notify(group, dispatch_get_main_queue(), ^{ NSLog(@"返回主线程");});
Blocking thread Groups
dispatch_group_t group = dispatch_group_create();//异步操作组dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{ for (int i = 0; i < 5; i ++) { //进入线程组 dispatch_group_enter(group); [NSThread sleepForTimeInterval:1.f]; NSLog(@"线程 --- %d",i); //离开线程组 dispatch_group_leave(group); }});//目的:先执行完前面的线程 再执行后面的线程//阻塞线程组dispatch_group_wait(group, DISPATCH_TIME_FOREVER);//异步操作队列dispatch_async(dispatch_get_global_queue(0, 0), ^{ NSLog(@"另一个线程执行了");});
pragma mark-Repeat
-(void) createqueue1{
Execute a thread repeatedly
The number of times the first parameter was executed repeatedly
Dispatch_apply (5, dispatch_get_global_queue (0, 0), ^ (size_t idx) {
NSLog (@ "thread execution ...");
});
}
pragma mark-Fence
-(void) createqueue2{
dispatch_queue_t queue = dispatch_get_global_queue(0,0);dispatch_async(queue, ^{ NSLog(@"线程1");});dispatch_async(queue, ^{ NSLog(@"线程2");});dispatch_barrier_async(queue, ^{ NSLog(@"barrier...");});dispatch_async(queue, ^{ NSLog(@"线程3");});
}
pragma mark-semaphore
-(void) createqueue3{
//信号量//创建信号量 参数为计数dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);dispatch_async(dispatch_get_global_queue(0, 0), ^{ //等待接收信号 接收信号要写在当前线程所有操作之前 计数-1 dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); NSLog(@"线程1执行...");});dispatch_async(dispatch_get_global_queue(0, 0), ^{ NSLog(@"线程2执行..."); //发送信号 在当前线程操作执行完毕之后 再发送信号 计数+1 dispatch_semaphore_signal(semaphore);});dispatch_async(dispatch_get_global_queue(0, 0), ^{ NSLog(@"线程3执行...");});dispatch_async(dispatch_get_global_queue(0, 0), ^{ NSLog(@"线程4执行...");});
}
iOS Development-multithreading