iOS multi-threaded distribution (1) nsthread (2) nsoperation (3) GCD
now to the following three analysis, I hope that there is not the right place to help my friends to guide twos.
1,nsthread
Pros: Nsthread relatively lightweight
Disadvantage: It is necessary to manage the thread life cycle, thread synchronization, and thread synchronization to lock up the data with some overhead.
Three ways to implement Nsthread:
1,
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadInitDoSomething) object:nil]; [thread start];
This method requires a thread to be manually opened.
2,
[NSThread detachNewThreadSelector:@selector(threadDetachDosomething) toTarget:self withObject:nil];
This convenient construction method does not need to be turned on manually
3,
[self performSelectorInBackground:@selector(backGround) withObject:nil];
This is the way the NSObject object comes with the background thread.
2,nsoperation
Advantages:
You don't need a manual relationship thread, you can focus on what you want to do, nsoperation we usually use its subclasses NSInvocationOperation NSBlockOperation or inherit Nsoperation's custom tasks, we often use tasks and queues together NSOperationQueue , An object is a task, more conducive to the management of the task, but also the advantage is that you can clearly determine the dependency relationship
Disadvantages:
He is a OC object, then the efficiency of the C function is lower, and based on GCD, then GCD will provide more comprehensive functions than him;
Use of Nsoperation:
1,
nsinvocationoperation *incocation = [[Nsinvocationoperation alloc] initwithtarget:self selector:@ Selector (invocationdosomething) Object:nil]; [Incocation start];
This approach leverages the target-action design pattern, allowing the responder to perform the task.
2,
nsblockoperation *block = [nsblockoperation blockoperationwithblock:^{NSLog (@ "%d,%@", [Nsthread Ismainthread], [Nsthread CurrentThread]); }]; [Block start]; The
uses the classic syntax block (syntax blocks) in OC. However, as with the above, if the subclass object using nsoperation alone must manually open the task.
3,
//nsoperationqueue The thread priority is only possible if it is serial nsoperationqueue *queue = [[Nsoperationqueue alloc] init]; Maximum concurrency, if the maximum number of patients is 1 o'clock, then the task in the queue will be serial, that is, perform a task to perform the next, if not 1, that is concurrent. Queue.maxconcurrentoperationcount = 1;
//Add block block task nsblockoperation *block = [nsblockoperation blockoperationwithblock:^{NSLog (@ "--0--%d,%@", [ Nsthread Ismainthread], [Nsthread CurrentThread]); }]; Set the priority of the task, only when the queue is listed as serial priority in order to play an absolute role [block setqueuepriority:nsoperationqueuepriorityveryhigh]; Nsblockoperation *block1 = [nsblockoperation blockoperationwithblock:^{NSLog (@ "--1--%d,%@", [Nsthread IsMainThread], [Nsthread CurrentThread]); }]; [Block1 Setqueuepriority:nsoperationqueueprioritynormal]; Nsblockoperation *block2 = [nsblockoperation blockoperationwithblock:^{NSLog (@ "--2--%d,%@", [Nsthread IsMainThread], [Nsthread CurrentThread]); }]; [Block2 Setqueuepriority:nsoperationqueuepriorityverylow]; Nsblockoperation *block3 = [nsblockoperation blockoperationwithblock:^{NSLog (@ "--3--%d,%@", [Nsthread IsMainThread], [Nsthread CurrentThread]); }]; [Block3 Setqueuepriority:nsoperationqueuepriorityveryhigh];
//设置以来关系,只有执行完block之后才会去执行block1,这叫做任务block1依赖于block,在项目开发中经常用到[block1 addDependency:block];//添加任务,任务为NSOperation对象的子类,添加到任务队列中之后会自动去执行,不需要start;[queue addOperation:block];[queue addOperation:block1];[queue addOperation:block2];[queue addOperation:block3];`
Nsoperationqueue is often used in development, such as when we do long tasks to download, using custom nsoperation subclasses and Nsoperationqueue together, each Nsoperation object is a task, The Nsoperationqueue, however, is the perfect role of the task-relationship player. Take the time to upload the demo to GitHub above, please and everyone timely attention. The dependency between tasks is also a perfect feature of nsoperation.
3,GCD (Key Introduction) GCD Introduction
gcd-(Grand Central Dispatch) is a technology developed by Apple. This technology can handle multiple tasks concurrently in multi-core hardware. It can also be said that GCD is a kind of extension and substitution technology of multithreading. GCD is supported after Mac OS x 10.6 and IOS 4.0.
Features of GCD
1.GCD can take advantage of multi-core hardware to handle multiple tasks concurrently. In other words, high efficiency.
The 2.GCD API provides many synchronous, asynchronous, and group-to-multitasking, synchronous, asynchronous operations. It is a technology that is more than a multi-threaded and bull X write.
3. Using GCD we can make it easier to take advantage of multi-core processor parallel processing tasks.
4.GCD after use without the program to manage the opening and closing of the thread, GCD will be on the system level to dynamically detect the system State, open and close the thread.
I fell in the wrong when I was learning gcd.
Read a lot of online blog, writing is particularly good, but I used to encounter some problems, such as synchronization and asynchronous and serial and parallel is always unclear, parallel and concurrency I always thought is a concept and so on, and now I first on these two issues to share my understanding to everyone,
Serial and parallel synchronization with synchronous asynchronous execution of the problem, serial parallel determines the execution of the task in the column (sequential) sequence of tasks within the serial queue execution, parallel queue according to system resources, there is no certain rules. And it gives us the feeling that multiple tasks are executed at the same time. Asynchronous and synchronous are just gcd in the face of the task block, synchronous ignore block code sequential execution, asynchronous is the normal block logic, and a moment to make callbacks, and is the advanced queue-line callback (in the serial queue).
Parallel and concurrent, due to the emergence of multi-core CPU now in parallel this talk, and a CPU core processing a task, two tasks or multiple tasks at the same time, but concurrency is the same CPU core back and forth, but because the time is very short round-trip dispatch, gives us the wrong feeling two tasks simultaneously execute is to dispatch the CPU to another task after executing some part of the task. A process of dispatching back and forth
The GCD in my heart
After some industry interview staff feedback, GCD is the multi-threaded inside is asked the most, so in gcd I put more energy, below we walk into my gcd time bar, here if there is insufficient place hope you can give me some insight, common progress.
GCD Queue Way Home column
dispatch_queue_t queue = dispatch_get_main_queue();
The primary queue is a serial queue, and the task is executed from top to bottom.
dispatch_async(queue, ^{ NSLog(@"这是第一个任务,当前线程是:%@, 是否主线程 :%d ", [NSThread currentThread], [[NSThread currentThread] isMainThread]); });
The above function means that the task inside the block is executed asynchronously in the main queue;
dispatch_sync(queue, ^{ NSLog(@"这是第一个任务,当前线程是:%@, 是否主线程 :%d ", [NSThread currentThread], [[NSThread currentThread] isMainThread]); });
The above line of code means to perform the task in the block block synchronously in the main line, but doing so will cause the main thread to feign death, unable to perform any operation, and regardless of whether you perform a series of tasks synchronously in any queue, it will be executed in the main thread. But the main thread does not appear suspended animation, so synchronization we seldom go to use. (where GCD is noticed)
Here we go. Synchronous execution of tasks and asynchronous execution of tasks for everyone to explain, the synchronous execution of tasks must be serial, asynchronous execution of tasks do not necessarily say parallel, and our network requests are similar, synchronous and sequential structure, the code line of execution, asynchronous and callback ideas, Perform the tasks in block blocks at some point.
Global queue
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
The global queue is a parallel queue, the task is parallel, take full advantage of the advantages of the multi-core CPU now, the first parameter is the priority of the queue, the second parameter is the Apple reserve parameter now has no practical effect we generally fill in 0.
dispatch_async(queue, ^{ NSLog(@"这是第一个任务,当前线程是:%@, 是否主线程 :%d ", [NSThread currentThread], [[NSThread currentThread] isMainThread]); });
If a series of tasks are added to the global queue, the task executes concurrently, so that the task is not predicted to be completed first.
Custom queues
dispatch_queue_t queue = dispatch_queue_create("com.zouhao", DISPATCH_QUEUE_CONCURRENT);
A custom queue can be either parallel or serial, the first parameter is the name of the queue, or it can be called a flag, and the second parameter is whether the queue is serial or parallel, representing the DISPATCH_QUEUE_CONCURRENT DISPATCH_QUEUE_SERIAL serial
dispatch_async(queue, ^{ NSLog(@"这是第一个任务,当前线程是:%@, 是否主线程 :%d ", [NSThread currentThread], [[NSThread currentThread] isMainThread]); });
This meaning is basically the same as the above two meanings, in the custom queue to add a task, the task is the block inside the business.
So the queue is here, let's take a look at some of the more conventional functions in GCD.
GCD delay execution, execute once, repeat, group task, Barrier, function pointer
This is some of the more conventional methods of use in GCD, but many of our friends often use strange logic to avoid using these methods in the development process, which is not seen or used. Let's take a look at the ways in which these methods work.
GCD Delay execution
//第一个参数是从现在开始,第二个参数是时间,dispatch_time_t delayInNanoSeconds =dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); //推迟两纳秒执行 dispatch_queue_t concurrentQueue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); //第一个参数只延迟时间,第二个参数是在那个队列里,第三个是任务, dispatch_after(delayInNanoSeconds, concurrentQueue, ^(void){ NSLog(@"Grand Center Dispatch!"); });
GCD Repeat execution
//有时候项目需求我们重复执行一个方法多次,比如我们常见的项目了面的倒计时的计时器,很多都是用GCD实现的。 dispatch_queue_t queue = dispatch_queue_create("com.zouhao", DISPATCH_QUEUE_SERIAL); dispatch_apply(3, queue, ^(size_t index) { NSLog(@"%zu, %@", index, [NSThread currentThread]); });
Here we look at dispatch_apply the function of a few parameters what is the meaning of the first parameter is repeated execution of the number of times, the second parameter is in that queue to perform the task, the third is the task, the block inside the parameter meaning is executed several times.
GCD executes only once
//只执行一次,单例对象创建的时候经常需要用到它 static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSLog(@"只会执行一次"); });
Here's a look at the Diapatch_once function followed by two parameters, the first parameter passed an address, the second parameter is a task, when executed into block blocks, the first parameter pointer to the address to write information, The next time the code is executed, it is found that the memory has been written and the block is no longer executed.
Only executes once in a single case using more, but we implement a singleton construction method, Class objcet = [[Class alloc] init]; put him in dispatch_once the block blocks, and then feel that their own singleton perfect, not really, if we call the init method outside or new objects, then we generally go back to control initialize In this method inside control, detailed can go to Baidu.
Grouping tasks
Sometimes when we develop the need to talk about some of the tasks in the queue added to a group inside to manage. We may need to do some other logic when the tasks within the group are executed.
dispatch_group_t group = dispatch_group_create(); dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_group_async(group, queue, ^{ NSLog(@"第一个任务 %d, %@", [NSThread isMainThread], [NSThread currentThread]); }); dispatch_group_async(group, queue, ^{ NSLog(@"第二个任务 %d, %@", [NSThread isMainThread], [NSThread currentThread]); });
So we're going to say that all the tasks in the queue are managed in groups, and this queue can be multiple, and when the task in the group is done, we use a new function.
//这个通知不能写在还所有任务之上,必须保证先在队列里面加入任务之后他才能够用,说简单的就是如果队列里面没有任务的时候他就会默认队列任务被执行完然后走通知 dispatch_group_notify(group, queue, ^{ NSLog(@"分组里面的最后一个任务了!"); });
But this task can not be added to the first group, otherwise this time the group is empty, the default all tasks are executed, directly to the notification block.
GCD Barrier
When we operate the database is often divided into write and read two processes, but multithreaded operations often have some problems, such as I read the time just in writing, this can not guarantee the feasibility of the data, this time when we write to block the read and write thread, so that it is in a waiting state.
dispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default, 0); Dispatch_async (Queue, ^{NSLog (@ "This is the first task to read data ... Thread is:%@, whether the main thread:%d ", [Nsthread CurrentThread], [[Nsthread CurrentThread] ismainthread]); }); Dispatch_async (Queue, ^{NSLog (@) This is the second task to read data ... Thread is:%@, whether the main thread:%d ", [Nsthread CurrentThread], [[Nsthread CurrentThread] ismainthread]); }); Dispatch_async (Queue, ^{NSLog (@ "This is the third task that reads data ... Thread is:%@, whether the main thread:%d ", [Nsthread CurrentThread], [[Nsthread CurrentThread] ismainthread]); }); Dispatch_barrier_async (Queue, ^{NSLog (@ "Your brother writes something to the database, do Not Disturb me"); Dispatch_async (Queue, ^{NSLog (@) This is the fourth task to read data ... Thread is:%@, whether the main thread:%d ", [Nsthread CurrentThread], [[Nsthread CurrentThread] ismainthread]); }); Dispatch_async (Queue, ^{NSLog (@) This is the fifth task to read data ... Thread is:%@, whether the main thread:%d ", [Nsthread CurrentThread], [[Nsthread CurrentThread] ismainthread]); }); Dispatch_async (Queue, ^{NSLog (@ "This is the sixth task that reads data ... Thread is:%@, whether the main thread:%d ", [Nsthread CurrentThread], [[Nsthread CurrentThread] ismainthread]); });
It is obvious that although it is executed asynchronously, it can be seen indispatch_barrierhAfter the method above the function is executeddispatch_barrierhThe following task is said to be in the waiting state, knowingdispatch_barrierhThe task inside the function is completed and then executed.
GCD function pointer
When we call the GCD function, we find that many methods are similar, except that there are more functions, and _f This is our function pointer, let's see what we have here.
Dispatch_async_f (Dispatch_get_main_queue (), "haha", func);//Dispatch_sync_f (< #dispatch_queue_t queue#> < #void *context#>, < #dispatch_function_t work#>)//Dispatch_after_f (< #dispatch_time_t When#>, < #dispatch_queue_t Queue#>, < #void *context#>, < #dispatch_function_t work#>)//Dispatch_apply_f (<# size_t Iterations#>, < #dispatch_queue_t Queue#>, < #void *context#>, < #void (*work) (void *, size_t) # >)//Dispatch_barrier_async_f (< #dispatch_queue_t Queue#>, < #void *context#>, < #dispatch_function_ T work#>)//Dispatch_barrier_sync_f (< #dispatch_queue_t Queue#>, < #void *context#>, < #dispatch_ function_t work#>)//Dispatch_group_async_f (< #dispatch_group_t Group#>, < #dispatch_queue_t Queue#>, < #void *context#>, < #dispatch_function_t work#>)//Dispatch_group_notify_f (< #dispatch_group_t group# , < #dispatch_queue_t Queue#>, < #void *context#>, < #dispatch_function_t work#>)//Dispatch_once_f (< #dispatch_once_t *predicate#>, < #void *context#>, < #dispatch_ function_t function#>)//Dispatch_set_finalizer_f (< #dispatch_object_t Object#>, < #dispatch_function_t finalizer#>)
When we implement the corresponding function, we must note that the return value of the function is void and the argument is void * type.
Why do we have a direct function call and a function pointer to implement the task body? It is obvious that block is the grammar block inside OC, but the function is the grammar inside the C language, so the function pointer this pattern must compare lower level, then the efficiency certainly will be higher than block this mode, but GCD native encapsulation is already very perfect, It is impossible to improve a lot of efficiency simply by talking about block switching to a function pointer, but in some fine-grained projects, you will pray for subtle improvements in efficiency.
iOS Multithreading Miscellaneous theory