Introduction to GCD usage of iOS multithreaded development

Source: Internet
Author: User
Tags gcd

We know that there are three main ways to do multithreaded programming in iOS: "Nsthread", "Nsoperation" and "GCD". Among them, "GCD" for Apple's official most recommended. This article will use a simple demo, a brief introduction to the use of GCD, as well as my gcd of the superficial understanding and learning experience.

List the reference articles first:

Http://www.cnblogs.com/kenshincui/p/3983982.html

Http://www.cnblogs.com/sunfrog/p/3305614.html

Http://mobile.51cto.com/iphone-446101.htm

Http://mobile.51cto.com/iphone-402964.htm

Http://mobile.51cto.com/iphone-386596.htm

Http://www.cnblogs.com/yangecnu/p/3164167.html

Http://www.dreamingwish.com/frontui/article/default/the-of-of-of-gcd-tutorial.html GCD Series tutorials are recommended here !

About "Nsthread" and "nsoperation" are actually involved in my previous blog posts, such as my blog post http://www.cnblogs.com/pigpigDD/p/3975852.html The Nsthread method is used to nstimer the child thread, and my blog: http://www.cnblogs.com/pigpigDD/p/3956308.html uses the Nsoperation subclass for network requests.

Let's say gcd.

In the use of GCD, the most basic and core concept is the dispatch queue. The dispatch queue is an object that can accept tasks and execute them in first-to-first-run order. The dispatch queue can be concurrent or serial. Concurrent tasks are carried out appropriately in parallel as Nsoperationqueue, based on the system load, and serial queues perform only a single task at a time. And, it can be nested to use.

1, parallel, serial, parallel concept:

Concurrency: On a single core, multiple threads, alternately rotating a task command, performing one task at a time

Serial: On a single core, a thread executes a task command sequentially, one task at a time

Parallel: Multiple threads on multiple cores, alternating task commands at the same time, multiple tasks executing at multiple cores at a time

Three kinds of queue types in 2,GCD

2.1, themain queue: the same as the main thread function. In fact, the task that is submitted to the main queue executes in the main thread. The main queue can be obtained by calling Dispatch_get_main_queue (). Because the main queue is associated with the main thread, this is a serial queue.

2.2, Globalqueues: the world queue is a concurrent queue and is shared by the entire process. There are three global queues in the process: High, Medium (default), low three priority queues. You can call the Dispatch_get_global_queue function to pass in the priority level to access the queue.

2.3, user queue: user Queue (GCD does not call this queue, but does not have a specific name to describe the queue, so we call it a user queue) is a dispatch_queue_create queue created with a function. These queues are serial and can be used to complete the synchronization mechanism. A bit like a mutex in a traditional thread.

2.3.1,dispatch_queue_t queue = dispatch_queue_create("com.dispatch.serial", dispatch_queue_serial ); generates a serial queue in which the blocks in the queue are executed in FIFO order, is actually a single thread execution. The first parameter is the name of the queue, which is useful when debugging a program, with all the same names as possible.

2.3.2,dispatch_queue_t queue = dispatch_queue_create("Com.dispatch.concurrent" , dispatch_queue_concurrent  ); generates a concurrent execution queue, and the block is distributed to multiple threads to execute.

3, using serial queue and concurrent queue, respectively, to demonstrate a demo

3.1, serial queue loading a series of pictures

Serial queue, as mentioned above, is a series of tasks in the queue, according to the advanced first processing method, "Queued in order" execution. I've created a serial queue myself here.

1 //2 //mainview.m3 //Gcddemo4 //5 //Created by Pigpigdaddy on 14-9-29.6 //Copyright (c) 2014 Pigpigdaddy. All rights reserved.7 //8 9 #import "MainView.h"Ten  One #defineRow_count 5 A #defineColumn_count 3 - #defineImageview_base_tag 100 -  the @interfaceMainView () -  -@property (nonatomic, strong) Nsmutablearray *DataArray; -@property (nonatomic, strong) Uiscrollview *ScrollView; +  - @end +  A @implementationMainView at  -- (ID) initWithFrame: (CGRect) Frame - { -Self =[Super Initwithframe:frame]; -     if(self) { -         //Initialization Code in [self initdata]; - [self initview]; to     } +     returnSelf ; - } the  *- (void) InitData $ {Panax Notoginseng     //an array that stores image addresses -Self.dataarray =[[Nsmutablearray alloc] init]; the      for(inti =0; i<row_count*column_count; i++) { +[Self.dataarray addobject:[nsstring stringWithFormat:@"Http://images.cnblogs.com/cnblogs_com/pigpigDD/616506/o_%d.png", i+1]]; A     } the } +  -- (void) Initview $ { $     //Create ScrollView -Self.scrollview =[[Uiscrollview alloc] initWithFrame:self.bounds]; - [self addSubview:self.scrollView]; the      -     //Create a Uiimageview for displayWuyi      for(inti =0; i<row_count; i++) { the          for(intj =0; j<column_count; J + +) { -Uiimageview *imageview = [[Uiimageview alloc] Initwithframe:cgrectmake ( -* (J%column_count) +5, the* (I%row_count) +5, -, the)]; WuImageview.tag = imageview_base_tag+j+i*3; - [Self.scrollview Addsubview:imageview]; About         } $     } -Self.scrollView.contentSize = Cgsizemake ( the,575); -      -     //button to start loading AUIButton *button =[UIButton Buttonwithtype:uibuttontypesystem]; +Button.backgroundcolor =[Uicolor Lightgraycolor]; theButton.frame = CGRectMake ( -, self.bounds.size.height- -, the, -); -[Button Settitle:@"Start loading"Forstate:uicontrolstatenormal]; $ [button addtarget:self action: @selector (LoadImage) forcontrolevents:uicontroleventtouchupinside]; the [self Addsubview:button]; the } the  the- (void) Downimage: (int) index{ -     //Get Pictures inNsurl *url = [Nsurl urlwithstring:[nsstring stringWithFormat:@"%@", [Self.dataarray Objectatindex:index]]; theNSData *data =[NSData Datawithcontentsofurl:url]; the      AboutUIImage *image =[UIImage Imagewithdata:data]; the      the     //get the main thread queue thedispatch_queue_t Mainqueue =dispatch_get_main_queue (); +     //update the downloaded picture in the main thread -Dispatch_async (Mainqueue, ^{ theUiimageview *imageview = (Uiimageview *) [self Viewwithtag:imageview_base_tag +index];BayiImageview.image =image; the     }); the } -  -  the- (void) LoadImage the { the     //Create a serial queue thedispatch_queue_t Serialqueue = Dispatch_queue_create ("Com.dispatch.serialQueue", dispatch_queue_serial); -      for(inti =0; i<row_count*column_count; i++) { theDispatch_async (Serialqueue, ^{ the [self downimage:i]; the         });94     } the } the  the @end

The Mainview here is a self-defined class that inherits from UIView and is initialized and loaded in the Rootviewcontroller instance of window.

Effect:

As you can see, when you click the "Start Loading" button, the pictures are downloaded and displayed in the order they were set. At the same time up and down sliding scrollview, because the download image data does not occur in the main thread, so there is no lag phenomenon.

3.2, concurrent queue loads a series of pictures

With concurrent queues, pictures are downloaded and displayed in shuffle. Here you only need to modify-(void) The LoadImage function implementation:

1-(void) loadimage{2     intcount=row_count*Column_count;3     4     //using global concurrent queues5     //dispatch_queue_t globalqueue = dispatch_get_global_queue (dispatch_queue_priority_default, 0);6     7     //use a concurrent queue that you create8dispatch_queue_t Concurrentqueue = Dispatch_queue_create ("Com.dispatch.concurrentQueue", dispatch_queue_concurrent);9     //Create multiple threads for populating picturesTen      for(intI=0; i<count; ++i) { One         //Execute queue Tasks asynchronously ADispatch_async (Concurrentqueue, ^{ - [self downimage:i]; -         }); the     } -}

As written in 2.2 and 2.3, concurrent queues can use global concurrent queues, or they can use the concurrent queues that they create.

The effect is as follows:

4. Note:

Whether it is a serial queue or a concurrent queue, only when the asynchronous call is really enabled multi-threading, using synchronous calls is actually running on the main thread! You can nslog [Nsthread CurrentThread] to analyze.

The above basic usage of GCD, and some basic concepts are summarized. I think the basic use of GCD is very simple, but there are many details in the GCD, and some advanced things, it is worth studying. Strive for in the future article, slowly summed up.

Introduction to GCD usage of iOS multithreaded development

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.