"IOS" Multithreading nsoperation

Source: Internet
Author: User

Nsoperation is the Apple package of a set of multi-threaded things, unlike GCD is pure C language, this is OC. But GCD will be faster than the next, but essentially nsoperation is a multi-GDC package.

A comparison of Nsoperation and GCD

GCD is based on C's underlying api,nsoperation belongs to Object-c class. The first introduction of iOS was the introduction of Nsoperation,ios4 and GCD and Nsoperationqueue, which were implemented internally using GCD.

GCD Advantages: GCD is mainly used in conjunction with block. The code is simple and efficient. Execution is slightly more efficient.

nsoperation relative to GCD
1,nsoperationhave more functions available, see the API specifically. Nsoperationqueue is achieved on the basis of GCD, butIt's GCD's higher level of abstraction.
2, in Nsoperationqueue, you canestablish a dependency between each nsoperation
3,nsoperationqueue Support Kvo。 You can monitor whether operation is executing (isexecuted), whether it ends (isfinished), whether it is canceled (Iscanceld)
4,GCD only supports FIFO queues, while nsoperationqueue can adjust the order in which the queues are executed (by adjusting weights)。 Nsoperationqueue can easily manage the priority between concurrency and nsoperation.

case of using nsoperation: There is a dependency between the operations, the operation needs to cancel the pause, concurrency management, control the priority between operations,limit the number of threads that can execute concurrentlyVolume.let the thread at some pointStop/continue tosuch as

case of using GCD: The general demand is very simple multi-threaded operation, with GCD can be, simple and efficient.

As far as programming principles are concerned, we typically need to use the high-level, encapsulated-perfect API as much as possible, using the underlying API when necessary.
When the requirements are simple, gcd may be a better choice, and the operation queue gives us more options.


Second, the simple operation of Nsoperation

?Nsoperation (Operation)withNsoperationqueue (Queue)to implement multithreading.?nothing likeGCDlike serial parallel What's, just take it and you can use it..

? Operation Dependency :nsoperation can be used to ensure the order of execution by setting dependencies . Execution of an operation must wait for another operation to complete before it continues execution.

use: [OP1 adddependency: op2] dependencies can be specified across queues. (cannot be turned into a cyclic dependency)

? can specify The priority of the queue.


the method of using Nsoperation (3 is equivalent ): (Note that nsoperation is an abstract class that must be implemented using his subclasses)
? Method 1, use nsoperation subclass nsinvocationoperation to create an operation . ? Method 2, using the nsoperation subclass nsblockoperation to create an action . (Same as the former effect ) ? Method 3, get a queue directly ( can be the home row , First run up ), and then addoperationwithblock is more convenient . ? Method 4, the direct custom nsoperation, realizes the corresponding method.

methods to implement Nsoperation, as well as suspend, pause, set maximum concurrency, set dependencies, etc..
@interface Xnviewcontroller ()/** nsoperation operation queue */@property (nonatomic, strong) Nsoperationqueue *queue;@ End@implementation xnviewcontroller//Add the operation to the queue-(Nsoperationqueue *) queue{if (!_queue) _queue = [[Nsoperationqueue A    Lloc] init]; return _queue;}    /** ============================= suspend suspend ============================= *//** pause Operation */-(ibaction) pause{//1. Determine if there is an action in the queue        if (Self.queue.operationCount = = 0) {NSLog (@ "no action");    Return }//2.        If it is not suspended (executing), it is necessary to suspend//only suspend the current queue that has not been scheduled (operations that are not scheduled to work on the thread) will be suspended if (!self.queue.issuspended) {NSLog (@ "paused");    [Self.queue Setsuspended:yes];    } else {NSLog (@ "has been paused");        }}/** continue Operation */-(ibaction) resume{//1. Determine if there is an action in the queue (Self.queue.operationCount = 0) {NSLog (@ "no action");    Return }//2.        If there is a pending operation, it is necessary to continue (restore) if (self.queue.isSuspended) {NSLog (@ "continue");    [Self.queue Setsuspended:no];    } else {NSLog (@ "executing"); }}/** ========================nsoperation specifies the dependency between operations ========================*/-(void) opdemo6{nsblockoperation *op1 = [nsblockoperation blockoperationwithblock:^{NSLog (@ "Downloading the complete works of Cang teacher ...    %@ ", [Nsthread CurrentThread]);        }]; Nsblockoperation *OP2 = [nsblockoperation blockoperationwithblock:^{NSLog (@ "is extracting the complete works of Cang teacher ...    %@ ", [Nsthread CurrentThread]);        }]; Nsblockoperation *OP3 = [nsblockoperation blockoperationwithblock:^{NSLog (@ "Saving to disk ...    %@ ", [Nsthread CurrentThread]);        }]; Nsblockoperation *OP4 = [nsblockoperation blockoperationwithblock:^{NSLog (@ "Download complete.)    %@ ", [Nsthread CurrentThread]);        }];    Specifies the "dependency" relationship between operations, the execution of one operation, which must wait for another operation to complete before it starts//dependencies are [OP2 ADDDEPENDENCY:OP1] that can be specified across queues;    [Op3 ADDDEPENDENCY:OP2];    [OP4 ADDDEPENDENCY:OP3];        When adding dependencies, be careful not to see cyclic dependencies//[OP3 ADDDEPENDENCY:OP4];    [Self.queue ADDOPERATION:OP1];    [Self.queue ADDOPERATION:OP2];    [Self.queue ADDOPERATION:OP3]; Master queue Update UI [[Nsoperationqueue Mainqueue] AddopeRATION:OP4];} /** ================================== Sets the maximum number of concurrent ==================================== */-(void) opDemo5{//sets the maximum number of concurrent queues, A queue is a scenario where the maximum number of concurrent/** is responsible for scheduling operations: 1> users limit the number of threads when using 3G, save power, save traffic (save money) 2> increase the number of threads when users use WiFi (LAN),        Improve the user experience maxconcurrentoperationcount if = = 1, similar to the serial queue Async method */self.queue.maxConcurrentOperationCount = 1; for (int i = 0; i < i++) {[Self.queue addoperationwithblock:^{NSLog (@ "Downloading%@%        D ", [Nsthread CurrentThread], i);    }]; }}/** ============================= block operation, add execution block ============================= */-(void) opdemo4{//Instantiate block operation N        Sblockoperation *op = [[Nsblockoperation alloc] init];    Sets the maximum number of concurrent (operations), does not limit the execution block!        Self.queue.maxConcurrentOperationCount = 2;    Add execution block [op addexecutionblock:^{NSLog (@ "Download Cang teacher complete 1%@", [Nsthread CurrentThread]);        }]; Continue adding block [op addexecutionblock:^{NSLog (@ "Download Cang teacher complete 2%@", [Nsthread CurrentthreAD]);        }];    Continue adding block [op addexecutionblock:^{NSLog (@ "Download Cang teacher complete 3%@", [Nsthread CurrentThread]);        }];    Continue adding block [op addexecutionblock:^{NSLog (@ "Download Cang teacher complete 4%@", [Nsthread CurrentThread]);        }];    Continue adding block [op addexecutionblock:^{NSLog (@ "Download Cang teacher complete 5%@", [Nsthread CurrentThread]);        }];    The start operation, in the main thread execution//If the number of execution blocks exceeds 1, will automatically go to other threads Execution (async)//The number of specific open threads, the system decision//execution block scheduling and operation of the schedule very much like//[op start]; [Self.queue Addoperation:op];}    /** ============================= Direct Add block operation ============================= */-(void) opdemo3{//As soon as the operation is added to the queue it will be dispatched immediately (executed) for (int i = 0; i < i++) {[Self.queue addoperationwithblock:^{NSLog (@ "Download starts%@-%@", [Nsthread        CurrentThread], @ (i));    }]; }//Add operations to the main queue [[Nsoperationqueue Mainqueue] addoperationwithblock:^{NSLog (@ "Download start%@-%@", [Nsthread cu    Rrentthread], nil); }];} /**============================= nsblockoperation =============================*/-(vOID) opdemo2{for (int i = 0; i < i++) {//Specify a block operation nsblockoperation *OP1 = [Nsblockoperation block        operationwithblock:^{NSLog (@ "Download start%@-%@", [Nsthread CurrentThread], @ (i));                }]; Adds a block action to the queue.    New thread [Self.queue ADDOPERATION:OP1]; }}/** =============================nsinvocationoperation============================= */-(void) opDemo1{for (int i = 0; I < 10; i++) {Nsinvocationoperation *OP1 = [[Nsinvocationoperation alloc] initwithtarget:self selector: @selector (Download:                ) object:@ (i)];        If it is started directly, it will be executed in the main thread//[OP1 start];    Added to the queue, it creates a new thread, asynchronously executes [self.queue ADDOPERATION:OP1]; }}-(void) Download: (ID) obj{NSLog (@ "Download start%@-%@", [Nsthread CurrentThread], obj);} @end

Custom Nsoperation:1, Inherit NSOperation2, re-Main method
@interface the. h header file on xnmyoperation:nsoperation@end//============================, the. m file =========================== = = @implementation xnmyoperation//just rewrite Main-(void) main{//    custom action, be sure to add your own auto-release pool    @autoreleasepool {        //... 。。。。。    }} @end

Reference:

Http://jianshu.io/p/d09e2638eb27

http://blog.csdn.net/hufengvip/article/details/11806897

http://blog.csdn.net/vieri_ch/article/details/21937859

Apple official documentation


Reprint Please specify source: http://blog.csdn.net/xn4545945



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.