Multithreading--nsoperation

Source: Internet
Author: User

First, Introduction

multithreaded development using nsoperation and Nsoperationqueue is similar to a thread pool in C #, as long as a nsoperation (which is actually required to use its subclasses nsinvocationoperation, Nsblockoperation) put it in Nsoperationqueue this queue will start in turn. Nsoperationqueue is responsible for managing and executing all nsoperation, making it easier to manage the total number of threads and to control the dependencies between threads in this process.

Nsoperation has two common subclasses for creating threading operations: Nsinvocationoperation and Nsblockoperation, which are essentially no different, but the latter using block form for code organization, using relatively convenient.

Second, nsblockoperation

////nsoperation Implementing Multithreading//multithread////Created by Kenshin Cui on 14-3-22.//Copyright (c) 2014 Kenshin Cui. All rights reserved.//#import "KCMainViewController.h"#import "KCImageData.h"#defineRow_count 5#defineColumn_count 3#defineRow_height 100#defineRow_width Row_height#defineCell_spacing 10@interfaceKcmainviewcontroller () {Nsmutablearray*_imageviews; Nsmutablearray*_imagenames;}@end@implementationKcmainviewcontroller- (void) viewdidload {[Super viewdidload]; [Self layoutui];}#pragmaMark Interface Layout-(void) layoutui{//Create multiple picture controls for displaying pictures_imageviews=[Nsmutablearray array];  for(intR=0; r<row_count; r++) {         for(intC=0; c<column_count; C++) {Uiimageview*imageview=[[uiimageview Alloc]initwithframe:cgrectmake (c*row_width+ (c*cell_spacing), r*ROW_HEIGHT+ (r*cell_spacing), Row_width, Row_height)]; Imageview.contentmode=Uiviewcontentmodescaleaspectfit;//Imageview.backgroundcolor=[uicolor Redcolor];[Self.view Addsubview:imageview];        [_imageviews Addobject:imageview]; }} UIButton*button=[UIButton Buttonwithtype:uibuttontyperoundedrect]; Button.frame=cgrectmake ( -, -, -, -); [Button Settitle:@"Loading Pictures"Forstate:uicontrolstatenormal]; //Add Method[button addtarget:self action: @selector (Loadimagewithmultithread) forControlEvents:    UIControlEventTouchUpInside];        [Self.view Addsubview:button]; //Create a picture link_imagenames=[Nsmutablearray array];  for(intI=0; i<image_count; i++) {[_imagenames addobject:[nsstring stringWithFormat:@"http://images.cnblogs.com/cnblogs_com/kenshincui/613474/o_%i.jpg", I]]; }    }#pragmaMark displays the picture to the interface-(void) Updateimagewithdata: (NSData *) data andindex: (int) index{UIImage*image=[UIImage Imagewithdata:data]; Uiimageview*imageview=_imageviews[index]; Imageview.image=image;}#pragmaMark Request picture Data-(NSData *) RequestData: (int) index{Nsurl*url=[Nsurl Urlwithstring:_imagenames[index]]; NSData*data=[NSData Datawithcontentsofurl:url]; returndata;}#pragmaMark loads the picture-(void) LoadImage: (NSNumber *) index{intI=[index IntegerValue]; //Request DataNSData *data=[self requestdata:i]; NSLog (@"%@", [Nsthread CurrentThread]); //updates the UI interface, where the main thread queue method is called (Mainqueue is the UI main thread)[[Nsoperationqueue Mainqueue] addoperationwithblock:^{[self updateimagewithdata:data andindex:i]; }];}#pragmaMark multi-Threaded Download pictures-(void) loadimagewithmultithread{intcount=row_count*Column_count; //Create an action queueNsoperationqueue *operationqueue=[[Nsoperationqueue alloc]init]; Operationqueue.maxconcurrentoperationcount=5;//set maximum number of concurrent threads//Create multiple threads for populating pictures     for(intI=0; i<count; ++i) {//Method 1: Create an action block to add to the queue//        //Creating multithreaded Operations//nsblockoperation *blockoperation=[nsblockoperation blockoperationwithblock:^{//[self loadimage:[nsnumber numberwithint:i]];//        }];//        //Create an action queue////[Operationqueue addoperation:blockoperation]; //Method 2: Add operations directly using the Operation queue[Operationqueue addoperationwithblock:^{[self loadimage:[nsnumber numberwithint:i]];            }]; }}@end

Compare before nsthread loading a picture It is found that the core code simplifies a lot, here the emphasis on two points:

    1. With the Nsblockoperation method, all operations do not have to define the method separately, and the problem of passing only one parameter is resolved.
    2. Call the Addoperationwithblock: method of the main thread queue to update the UI without having to define a parameter entity (before you have to define a kcimagedata problem that only passes one parameter).
    3. Multithreaded development with Nsoperation can set the maximum concurrent threads, effectively control the threads (the above code runs you will find that only a limited number of threads are created when printing the current process, as the above code sets the maximum thread count to 5, the picture is basically five loads at a time).

Third, the execution order of the thread

It is difficult to control the order in which threads are executed before using Nsthread, but using nsoperation is much easier, and each nsoperation can set dependent threads. Assuming that operation a relies on action B, the thread operations queue performs a B operation first when the thread is started, and then executes a. For the previous requirement to load the last diagram first, just set the dependent thread for the previous thread operation as the last action. Modify the image loading method as follows:

-(void) loadimagewithmultithread{intcount=row_count*Column_count; //Create an action queueNsoperationqueue *operationqueue=[[Nsoperationqueue alloc]init]; Operationqueue.maxconcurrentoperationcount=5;//set maximum number of concurrent threadsnsblockoperation*lastblockoperation=[nsblockoperation blockoperationwithblock:^{[Self loadimage:[nsnumber numberwithint: (Count-1)]];    }]; //Create multiple threads for populating pictures     for(intI=0; i<count-1; ++i) {//Method 1: Create an action block to add to the queue//Creating multithreaded OperationsNsblockoperation *blockoperation=[nsblockoperation blockoperationwithblock:^{[self loadimage:[nsnumber numberwithint:i]];        }]; //to set a dependency action for the last picture load Operation[Blockoperation adddependency:lastblockoperation];            [Operationqueue addoperation:blockoperation]; }    //Add the last picture's load operation to the thread queue[Operationqueue addoperation:lastblockoperation];}

Operating effect:

You can see that while the last picture was loaded, the operation was finally added to the operation queue, but it was executed by the first one. An operation dependency can be set to multiple, for example a depends on B, B depends on C ... However, do not set a circular dependency (for example, a relies on b,b dependent on C,c and a), otherwise it will not be executed.

Multithreading--nsoperation

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.