1 GCD
It is a pure C language, it is designed for multi-core parallel operation. You can automatically manage the life cycle of a thread.
GCD are task-and queue-oriented, not thread-oriented. He has two keywords "task" "queue".
The main steps for using GCD are:
1 Customizing tasks
2 tasks added to the queue, queue support FIFO principle
#基本形式如下
dispath_queue_t queue = dispath_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFULT,0);dispath_async(queue,^{ //任务代码段});
1.1 Task 1.1.1 Synchronization mode
Executes in the current thread and does not have the ability to open threads.
dispath_sync( queue,block); //在队列中执行 block 所定义的任务,以同步的方式
1.1.2 Async Mode
Executes in a new thread with the ability to open a new thread
dispath_async(queue,block); //在队列中执行 block 所定义的任务,以异步的方式
Determines whether you have the ability to open new threads
1.2 Queue 1.2.1 Parallel queue
Parallel queue, the task in the queue, in parallel, multi-tasking simultaneously.
In general, we are using a global concurrency queue. Here's how to get a global concurrency queue:
//默认的写法,获取全局并发队列。前一个参数是优先级默认,后面一个参数是苹果保留的参数dispath_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
1.2.2 Serial Queue
In a serial queue, the characters in the queue are in a serial fashion. Perform one task before performing another task.
There are two types of serial queues, one is a manually created serial queue and the other is the home row
1.2.2.1 Manually creating queues
//默认写法,第一个参数是队列名称,随便填写;第二个参数是队列属性,一般情况下写 NULLdispatch_queue_create("queueName",NULL);
1.2.2.2 Home Row
//默认写法dispath_get_main_queue();主队列的任务执行,都是在主线程中进行的,一般用来做线程间的通信。
2 Common Combinations 2.1 Async mode + concurrent Queue (most commonly used)
① will create a new thread
② Concurrent execution of tasks
In the following example, Task 1 and Task 2 are executed concurrently
//实例代码//①获取全局并发队列dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);//②异步方式处理任务1dispatch_async(queue,^{ NSLog("下载图片1--%@",[NSThread currentThread]);});//②异步方式处理任务2dispatch_async(queue,^{ NSLog("下载图片2--%@",[NSThread currentThread]);});
2.2 Async mode + serial queue
① creates a new thread because it is executed serially, and typically only creates a new thread.
Tasks in the ② queue are executed serially: Task 1 and Task 2 are serially executed
//示例代码//①手动创建串行队列dispatch_queue_t queue = dispatch_queue_create("queueName",NULL);//②异步方式处理任务1dispatch_async(queue,^{ NSLog("正在下载图片1---%@",[NSThread currentThread]);});//②异步方式处理任务2dispatch_async(queue,^{ NSLog("正在下载图片2---%@",[NSThread currentThread]);});
2.3 Synchronous mode + concurrent queue
① does not create threads
The concurrency of the ② concurrent queue disappears, and all tasks in the queue are executed serially.
//示例代码//①获取全局并发队列dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);//②同步执行任务1dispatch_sync(queue,^{ NSLog(@"下载图片1---%@",[NSThread currentThread]);});//②同步执行任务2dispatch_sync(queue,^{ NSLog(@"下载图片2---%@",[NSThread currentThread]);});
2.4 Synchronous mode + serial queue
① does not create a new thread
② serial execution of all tasks in the serial queue
//示例代码//①手动创建串行队列dispatch_queue_t queue = dispatch_queue_create("queueName",NULL);//②同步执行任务1dispatch_sync(queue,^{ NSLog(@"正在下载图片1-----%@",[]NSThread currentThread]);});//②同步执行任务2dispatch_sync(queue,^{ NSLog(@"正在下载图片2-----%@",[]NSThread currentThread]);});
2.5 Primary Queue + Async (home row is also serial queue)
The ① Home column is a special queue, and while the async mode has the ability to create new threads, it is not actually possible to create new threads
② All tasks are performed serially in the main queue, i.e., in the primary thread, and are generally used to communicate between processes.
//①获取当前的主队列dispatch_queue_t queue = dispatch_get_main_queue();//②异步方式执行dispatch_async(queue,^{ NSLog(@"正在下载图片---%@",[NSThread currentThread]);});
2.6 Primary Queue + synchronization mode (home row is also serial queue)
- This way, the whole program will get stuck, without
-
The current execution of the following program is performed in the main thread, and when performing to the second step, the following tasks need to be added to the main queue for serial execution. Because it is serial execution, the main thread must wait until the end of the second step to continue execution, but the second step is to load the task to the end of the home column, which must wait until the main thread queue has completed before executing, so it is stuck in a dead state.
//1获取主队列dispatch_queue_t queue = dispatch_get_main_queue();//2同步执行主队列dispatch_sync(queue,^{ NSLog(@"正在执行。。。");});
3 Memory management for queues
The principles to be followed:
* All function names with create\copy\new\retain and other words, should not need to use this data when the release operation
* GCD data type, no need to release under Arc
* The data type of the CF (Core Foundation) requires manual release in both ARC and MRC environments.
Example:
* Cfrelease (ID);
NSDictionary *dict = @{@"1":@"1"};CFDictionaryRef dictCF = (__bridge CFDictionaryRef)(dict);CFRelease(dictCF);
4 Communication between threads
For example, click the View of the controller, download an image from the Web on the sub-thread, and then update the button's picture in the main thread after the download is complete.
//1 获取全局并发队列dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);//2 异步方式下载图片dispatch_async(queue, ^{ NSString *str = @"http://u1.img.mobile.sina.cn/public/files/image/600x150_img577f313ec621a.png"; NSURL *url = [NSURL URLWithString:str]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *image = [UIImage imageWithData:data]; //3 回到主线程,给 UIButton 设置图片 dispatch_async(dispatch_get_main_queue(), ^{ [self.button setImage:image forState:UIControlStateNormal]; });});
5 time delay to perform operation
In the program design, there are three ways of delaying execution
5.1 Sleep
To do a delay operation, this method only needs to execute the following code before the deferred operation
//使当前线程睡眠3秒钟后再次执行[NSThread sleepForTimeInterval:3]
Disadvantage: The thread that is currently calling will be stuck and the entire thread will stall. If the main thread is stuck, it means that the UI is greatly affected.
5.2 Performselectorafter
//当3秒后,执行 download 方法。3秒后在主线程中执行该操作[self performSelector:@selector(download) withObject:nil afterDelay:3]
5.3 GCD
Depending on the type of queue, you can decide which thread to execute after the delay, either by specifying it in a global concurrent queue or by specifying execution in the primary queue.
//dispatch_queue_t queue = dispatch_get_main_queue();dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), queue, ^{ NSLog(@"延时操作---%@",[NSThread currentThread]);});
6 Disposable Code
A piece of code, in the process of running, no matter how many times the call, actually changed the code only once, this is the one-time code
For example: After clicking on the interface, start downloading the image. If the code to download the picture is not a one-time code, every click of the interface, you need to download again, obviously not in line with the actual situation. It can also be implemented in other ways (defining variables or defining identities), but one-time code is the simplest operation.
static dispatch_once_t oneceToken;dispatch_once(&onceToken,^{ //想要只执行一次的代码 //.....});
7 Queue Groups
A queue group is an object that contains a queue that automatically calls the method of the response when a task in the queue finishes executing, which is the queue group.
Demand:
需要从网络上下载一张图片,然后再下载一张 logo 图片,用 logo 做水印。如果按照顺序,先下载图片,再下载 logo,最后进行图片水印叠加,会比较耗时。最好的办法是 两张图片分别放到两个线程中进行,当两个图片全部下载好之后,再进行组装。
Implementation ideas:
采用队列组,手动创建一个队列组,使用dispatch_group_async(group,queue,^{})来开辟新线程执行下载操作。当队列组中的队列任务全部结束之后,会自动调用 dispatch_group_notify(queue,^{})函数,也就是说我们可以将合并水印的操作放在这个函数中进行。
Sample code
1 Get global concurrent queue dispatch_queue_t queue = Dispatch_get_global_queue (dispatch_queue_priority--default,0);//2 Create Queue group-if yes In the MRC environment, the release operation is required: Dispatch_release (group);d ispatch_group_t group = Dispatch_group_create (); 3 download Image 1__block UIImage *image1 = nil; The __block modifier is for the block to have access to the variable Dispatch_group_async (group,queue,^{nsstring *str = @ "Http://image1.png"; Nsurl *url = [Nsurl urlwithstring:str]; NSData *data = [NSData Datawithcontentsofurl:url]; Image1 = [UIImage imagewithdata:data];}); /4 Download Image 2__block UIImage *image2 = nil; The __block modifier is for the block to have access to the variable Dispatch_group_async (group,queue,^{nsstring *str = @ "Http://image2.png"; Nsurl *url = [Nsurl urlwithstring:str]; NSData *data = [NSData Datawithcontentsofurl:url]; Image2 = [UIImage imagewithdata:data];}); /5 Merge Picture--group after all the queues in the queue have finished executing, the following function is automatically called dispatch_group_notify (group,queue,^{//5.1 to open the current graphics context Uigraphicsbeginimagecontextwithoptions (image1.size,no,0.0); 5.2 Draw Image1 in context [Image1 Drawinrect:cgrectmakE (0,0,image1.size.width,image1). Size.Height)]; 5.3 Draw Image2 in context [Image2 Drawinrect:cgrectmake (0,0,100.50)]; 5.4 Get picture of current context UIImage *image = Uigraphicsgetimagefromcurrentimagecontext (); 5.6 Back to the main thread, refresh UI dispatch_async (dispath_get_main_queue,^{self.imageView.image = image; });});
iOS Multithreading--Next (GCD)