The Nsoperationqueue of multi-threading tools

Source: Internet
Author: User
Tags usleep

Pros: Multithreaded programming using the Nsoperationqueue method, not being able to manage threads directly (invisible threads) like nsthread, and do not need to be managed, but indirectly InterventionThread. 1.NSOperation is an abstract class, code and data to encapsulate a single taskabstract class, so you cannot use the class directly,Instead, create subclasses or some system-defined subclasses (Nsinvocationoperation or nsblockoperation) to accomplish the actual tasks.  Creation of 2.NSOperation subclasses
Subclass Cnoperation Creation Inherits nsoperation cnoperation* op = [[Cnoperation alloc]init];//nsoperation is not executed by default and must call the Start method [op STA  RT]; #import "CNOperation.h"

@implementation cnoperation-(void) main{NSLog (@ "do something");
} @end
3. Nsoperation sub-class with system's own (nsinvocationoperation or Nsblockoperation )  
1. Create nsinvocationoperation nsinvocationoperation* IOP = [[Nsinvocationoperation alloc]initwithtarget:self    Selector: @selector (invoaction) Object:nil]; [IOP start];
 
2. Creatensblockoperation1. System Blocknsblockoperation* bop = [nsblockoperation blockoperationwithblock:^{NSLog (@ "Do other something");
}]; [Bop start];2. Custom BlockIn the Cnoperation class, you can also @property (copy) void (^block) (void) by writing the Block yourself. Call block-(void) in the main method in the Cnoperation class main{
Call Block
if (_block) {
_block (); } cnoperation* cn = [[Cnoperation alloc]init];
Block implementation
[CN setblock:^{NSLog (@ "do something");    Dead Loop//while (true) {////}}];         [CN start]; NSLog (@ "Because there is a dead loop, so the statement will never be printed out");Summary:Nsoperation is not executed by default and must be called by the Start method and executed by default in the current thread, which is the default synchronous execution.  What is the real synchronous execution? if the block executes, start will not execute.How to invoke it? For example, in the above code, the default program first go to Start,start and call the Main,main and call the block, layer calls, after the call to execute, so block first execute start after execution, first print do something
4.NSOperationQueue a Nsoperationqueue object is not a thread, but a thread manager that can help us create new threads automatically. Depends on the maximum number of parallel queues. The Nsoperation object is added to the queue, and the default becomes asynchronous execution (not the current thread). 1. Interpreting synchronous execution and asynchronous execution, demonstratingHow the queue is implemented in asynchronous execution
cnoperation* cn = [[Cnoperation alloc]init];
Block implementation
[CN setblock:^{
NSLog (@ "do something");
Dead loop
while (true) {
}    }];
Synchronous Execution (performing the OP task on the current thread), the start will never be executed because there is a dead loop in the block, the block executes, and start is not executed
[CN start]; Asynchronous Execution (performing an OP task on another thread), the start will not be executed, and the subsequent code will be printed, because the asynchronous execution is performed by the execution of the block, start executes//asynchronous execution only needs to put the start method into the new thread, The Performselectorinbackground is an implicitly created thread, and we have no way to manage him, so we use the queue to create new threads, which is what is newly learned [CN performselectorinbackground:@    Selector (start) Withobject:nil]; NSLog (@ "AAA");
5. Create Nsoperationqueue  
1. Create Nsoperationqueue //Create thread manager nsoperationqueue* OpQ = [[Nsoperationqueue alloc]init];
2. Add a single operation to the queue nsblockoperation* BOP1 = [Nsblockoperation blockoperationwithblock:^{
NSLog (@ "Bop1 ...");
NSLog (@ "bop1:%@", [Nsthread CurrentThread]);
Usleep (1000000);

}];
//after you add to the queue , you do not need to start manually and will automatically begin execution
[Bop1 start];


nsblockoperation* BOP2 = [Nsblockoperation blockoperationwithblock:^{

NSLog (@ "Bop2 ...");
NSLog (@ "bop2:%@", [Nsthread CurrentThread]);
Usleep (1000000);


}];
[Bop2 start];

The nsoperation that are added to the queue are automatically executed, and the time to execute depends on the two factors one is dependent on. One is the priority level
[OpQ addoperation:bop1];//[OpQ ADDOPERATION:BOP2];
3. You can add multiple operation to the Queue at the same time You can add multiple operation to the queue at the same time//waituntilfinished set to No or you can execute subsequent statements without waiting for the queue to complete --ok---
Waituntilfinished is set to YES to wait for the queue to execute after it is all executed before executing the following statement [OpQ    ADDOPERATIONS:@[BOP1,BOP2] Waituntilfinished:yes]; NSLog (@ "-----OK-----");
4. Maximum number of concurrent queues//set queue Max concurrency//MAX parallel number is 1 o'clock, all op will be serial, does not mean only one thread 1-1-2-2 Opq.maxconcurrentoperationcount = 1;// If you do not set the maximum concurrent book printing operation may alternately appear 2-1-2-1
5. You can implicitly add a operation to the Queue This means that you do not need to create a operation yourself, but instead let the queue create it yourself [OpQ addoperationwithblock:^{NSLog (@ "can implicitly add a operation to the queue");
NSLog (@ "keyi:%@", [Nsthread CurrentThread]);

Usleep (1000000);
}];
6. Add a nsoperation dependent object   Note: Never modify the state of the Nsoperation object after Nsoperation is added to the queue, because operation at this point may run at any time, so you can only view the state of the Nsoperation object, such as whether it is running, waiting to run, completed, and so on. 6.1 Add dependency Add dependency success is a prerequisite that operation must be added to the queue because automatic execution is likely to generate dependencies
Nsoperationqueue *queue = [[Nsoperationqueue alloc] init];
       nsblockoperation *operation1 = [Nsblockoperation blockoperationwithblock:^ ()                                      {                                           NSLog (@ "1th operation, 1:%@", [Nsthread CurrentThread]);                                     }];    nsblockoperation *operation2 = [ Nsblockoperation blockoperationwithblock:^ ()                                       {                                          NSLog (@ "2nd operation, 2:%@", [Nsthread CurrentThread]);
}];
Nsblockoperation *operation3 = [Nsblockoperation blockoperationwithblock:^ () { NSLog (@ "3rd operation, 3:%@", [Nsthread CurrentThread]);
}]; adding dependencies//dependencies can affect the order in which the Nsoperation objects are executed in the queue//Add dependent success, the operation must be added to the queue//Add dependencies and will be executed by default on the same thread, not exactly [    Operation1 Adddependency:operation2];       [Operation1 Adddependency:operation3]; // When multiple dependencies are added, the above is not correct, but should be changed to operation1 will be executed in the last executed thread of dependent operation Execution  It means that OP2 relies on OP1 so OP2 executes first, and OP3 relies on OP1 so OP3 executes first, then OP2 and op3 who executes first? OP3 and OP2 do not have to be executed first, OP1 will execute in the last thread of dependency, because the current print op2 last execution, so OP1 and OP2 are on the same thread
Setting the priority level
First, the order of execution is determined based on the dependency relationship, and then the priority is sorted according to the precondition of satisfying the dependency relationship.
Operation2.qualityofservice = nsqualityofserviceuserinteractive;
Operation3.qualityofservice = Nsqualityofservicebackground;
//
Note: You cannot create ring dependencies, such as a dependent b,b dependency A, which is wrong,//[Operation2 Adddependency:operation1]; OP2 execution OP1 cannot execute, OP1 execution is not complete OP2 cannot execute
Add dependency before adding to queue
Print out the order of execution is indeterminate
Operation added to the queue should not modify properties
[Queue Addoperation:operation1];
[Queue Addoperation:operation2]; [Queue Addoperation:operation3];
7. Nsoperationqueue Cancel, wait, pause and Continue the queue  
nsoperationqueue* queue = [[Nsoperationqueue alloc]init];

nsblockoperation* OP1 = [Nsblockoperation blockoperationwithblock:^{
NSLog (@ "Block Opreation1");
NSLog (@ "1:%@", [Nsthread CurrentThread]);
}];

nsblockoperation* OP2 = [Nsblockoperation blockoperationwithblock:^{
NSLog (@ "Block Opreation2");
NSLog (@ "2:%@", [Nsthread CurrentThread]);

Cancel OP1 must be canceled before OP1 execution, no is invalid
[OP1 Cancel]; Time outnot operation pause and continue, the task cannot be paused after it has started, but the queue is paused and canceled, the queue is paused, the operation that is currently executing is not paused, and the pause just stops opening the new waiting operation [Queue Setsuspended:yes]; Because Operation2 is executing, it is not paused and Operation1 is paused
}];
Do not add dependencies before, op start execution can not be canceled, still OP1 and OP2 are executed out//But add dependency is not the same, add dependency after op2 first execution, at this time OP1 has not been executed, this can be canceled OP1 [OP1 ADDDEPENDENCY:OP2] ;
[Queue ADDOPERATION:OP1];
[Queue ADDOPERATION:OP2];
Cancel all operations in the queue
[Queue cancelalloperations];
Waiting for the current thread to die
Wait for OP2 execution, then execute//[OP2 waituntilfinished]; Wait for the queue to execute after all operations have finished executing
[Queue waituntilalloperationsarefinished];
NSLog (@ ".....");
Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (3 * nsec_per_sec)), Dispatch_get_main_queue (), ^{
Delay after 3 seconds to continue queue
[Queue Setsuspended:no]; });

The Nsoperationqueue of multi-threading tools

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.