Multi-Threading Technology for iOS development (Nsthread, Operationqueue, GCD)

Source: Internet
Author: User
Tags gcd

In the previous blog if the use of asynchronous requests, but also used to third-party things, there is no serious used in iOS multi-threaded things. In fact, multi-threaded things are still very important, if for the previous learning of the operating system of small partners, understand the multi-threaded things are relatively easy, today do a small demo to learn more about the multi-threaded in iOS things. Perhaps the following things will be more boring, but it is more practical.

Multi-threaded use or more, nonsense less said, the following two are the final results of our experiment today, should be relatively full, small partners from the figure to analyze the specific functions of it:

Function Description:

1, click the sync request picture, observe the whole UI changes, and click the Test button, Red will turn green.

2, Nsthread button, is the Nsthread way to create the thread and perform the appropriate action.

3, the block Operation button is to create the operation with block, and execute in the operation queue, the following is the invocation operation

4, serial is the serial queue in GCD, concurrent is the parallel queue in GCD

OK, the salted egg up here first, the code should go.

First, the preparatory stage

1. Whether you write with code, storyboard or Xib, first initialize the controls you want above to use the

2. Click the Test UI button to change the color of the label below:

1//change lable color, exchange between red and green color 2-(ibaction) Taptestbutton: (ID) sender {3     static int i = 1; 4     if (i = = 1) {5         _tes Tlabel.backgroundcolor = [Uicolor Redcolor]; 6         i = 0; 7     } 8     Else 9     {         _testlabel.backgroundcolor = [Uicolor greencolor];11         i = 1;12     }13< C10/>14}

3. Get the picture from the network and use the main thread to show the process call situation

1//Get picture data from Wang ' Lu 2-(NSData *) Getimagedata 3 {4      5     _count + +; 6     int count = _count;
Thread starts to start 7 nsstring *str = [NSString stringwithformat:@ "%d. Thread%@", Count,[nsthread CurrentThread]];
NSLog (@ "%@", str);
8     NSData *data; 9     [nsthread sleepfortimeinterval:0.5];10     data = [NSData Datawithcontentsofurl:[nsurl Urlwithstring:imageurl]];11     NSString *str = [NSString stringwithformat:@ "%d. Thread%@ complete", Count,[nsthread Currentthread]];13     //The task of requesting data is resolved by another thread, so the contents of Logtextview are updated by the main thread and only the main thread can update UI14     [self Performselectoronmainthread: @selector (updatetextviewwithstring:) withobject:str waituntildone:yes];15     return DATA;16}

4. The above uses the main thread to invoke the Updatetextviewwithstring method, because only the main thread can update Ui,updatetextviewwithstring: This method is responsible for displaying the execution information of the thread on the view, the code is as follows:

1//Display picture request condition on Viewcontroller 2-(void) updatetextviewwithstring: (NSString *) STR3 {4     nsstring *old_str = [NSString stringwithformat:@ "%@\n%@", _logtextview.text, str];5     6     _logtextview.text = old_str;7     //Change the color of the label, Easy to observe 8     [self taptestbutton:nil];9}

5. Load the requested picture onto the ImageView

1//Update picture 2-(void) Updateimagewithdata: (NSData *) data3 {4     UIImage *image = [UIImage imagewithdata:data];5     [_ Testimage Setimage:image];6}

6. Load the image, that is, the request data is displayed on the ImageView

1//Request data by other threads, updated UI2-(void) Loadimagewiththreadname by the main thread: (NSString *) ThreadName3 {4     [[Nsthread CurrentThread] Setname:threadname];5     6     nsdata *data = [self getimagedata];7     [self performselectoronmainthread:@ Selector (updateimagewithdata:) Withobject:data waituntildone:yes];8}

Second, through a variety of ways to

1. Synchronous request picture test, request data and update UI are placed in the main thread sequence execution, so that when the data is requested by the UI will be stuck, the code is as follows;

1//Sync request picture, view blocked because the main thread is occupied, unable to make view update 2-(ibaction) Tapbutton: (ID) Sender {3     nsdata *data = [self getimagedata];4     [Self updateimagewithdata:data];5}

2.NSThread Create a thread test, using the Detachnewthreadselector method to create a new thread automatically starts and executes without calling the Start method. The code is as follows:

1//nsthread2-(ibaction) TapButton2: (ID) Sender {3     //Click once button to create a new thread request picture data 4 for     (int i = 0;i <; i + +) { 5         [Nsthread detachnewthreadselector: @selector (loadimagewiththreadname:) totarget:self withobject:@ "NSThread"] ; 6     }7  }

   

For 3.NSInvocationOperation use, create a new call operation and then add it to the queue to execute, with the following code:

1//nsinvocationoperation 2-(ibaction) Tapinvocationoperation: (ID) Sender {3   4      5     ///above the call operation needs to be placed in the call queue to execute  6     //Create Operation Queue 7     nsoperationqueue *operationqueue = [[Nsoperationqueue alloc] init]; 8  9 for     (int i = 0;i < 10; i + +) {         //instantiate a call operation to execute data request         nsinvocationoperation *invocationoperation = [[Nsinvocationoperation alloc] Initwithtarget:self selector: @selector (loadimagewiththreadname:) object:@ "Invocation"];12         //Put the above call action in the Operation queue, The queue automatically opens a thread that calls the method we specify         [Operationqueue addoperation:invocationoperation];14     }15}

4.block operation, create a new block operation and add it to the queue to execute, the code is as follows:

1//blockoperation 2-(ibaction) Tapblockoperation: (ID) Sender {3     __weak __block viewcontroller *copy_self = self; 4
   5     //Create Blockoperation 6     nsblockoperation *blockoperation = [nsblockoperation blockoperationwithblock:^{7         [copy_self loadimagewiththreadname:@ "Block"]; 8     }]; 9     //Add to Operation queue     nsoperationqueue *operationqueue = [[Nsoperationqueue alloc] init];12     [ Operationqueue addoperation:blockoperation];13     for     (int i = 0;i <; i + +) {n         //Another way 17< C14/>[operationqueue addoperationwithblock:^{18             [copy_self loadimagewiththreadname:@ "Block"];19         }];20     }21}

Serial Queue in 5.GCD:

1//Serial Queue 2-(ibaction) Tapgcdserialqueue: (ID) Sender {3     //Create serial queue 4     dispatch_queue_t serialqueue = Dispatch_queue _create ("Myserialqueue", dispatch_queue_serial); 5      6      7     __weak __block viewcontroller *copy_self = self, 8      9     for     (int i = 0;i <; i + +) {11< c8/>//Asynchronous Execution Queue         Dispatch_async (serialqueue, ^{13             [copy_self loadimagewiththreadname:@ "Serial"];14         } );     }16     18}

Parallel queues in 6.GCD:

1//Parallel Queue 2-(ibaction) Tapgcdconcurrentqueue: (ID) Sender {3     //Create parallel Queue 4     dispatch_queue_t concurrentqueue = Dispatch_queue_create ("Myconcurrentqueue", dispatch_queue_concurrent); 5     __weak __block viewcontroller *copy_self = self, 6      7 for     (int i = 0;i <; i + +) {8         //Asynchronous Execution Queue 9         Dispatch_async (Concurrentqueue, ^{10             [copy_self loadimagewiththreadname:@ "Concurrent"];11         });     15}

The above is the corresponding method of each button, the following is the result of the execution:

Iii. synchronization between threads (add a sync lock to our thread)

In the operating system to talk about multi-threading when a noun called dirty data, that is, multiple threads operation of the same resource caused by the following changes in code, so that the data problems, and then use a synchronous lock to solve the problem

1. There are two statements in the Getimagedata method (the 3rd method in heading one). This is used to display the thread's label. The markings above are not duplicated.

1     _count ++;2     int count = _count;

Add a delay between the two statements, as follows:

    _count + +;    [Nsthread sleepfortimeinterval:1];    int count = _count;

If run, there will be a lot of labels are repeated, one, __count is a member variable, multiple threads on this he operates, so there will be inconsistent labeling situation, below we add a synchronous lock

(1) with Nslock and synchronous lock, the code is as follows:

1     //via Nslock plus lock 2     [_lock lock];3     _count ++;4     [nsthread sleepfortimeinterval:1];5     int count = _ Count;6     [_lock unlock];

(2) via @synchronized Plus sync Lock, the code is as follows:

1     //via synchronized lock 2     int count;3     @synchronized (self) {4         _count ++;5         [nsthread Sleepfortimeinterval:1];6          count = _count;7     }

Before and after the lock operation effect is as follows:

The sequence in which the GCD serial queue starts is executed in the following order, in FIFO order in one thread:

Parallel queues in GCD are executed concurrently on different threads:

Today the content of the blog is still very much, if the previous contact with Java multithreading, or other languages in the multi-threaded words, should not understand the problem.

Multi-Threading Technology for iOS development (Nsthread, Operationqueue, GCD)

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.