Introduction and simple use of the iOS development multithreaded article---GCD

Source: Internet
Author: User
Tags gcd

Introduction to 1.GCD:

The Grand Central Dispatch abbreviation (GCD) is the technology developed by Apple to optimize applications that support multi-core processors and other symmetric multi-processing systems. This is based on the thread pool pattern that the task executes in parallel. And it's pure C, and it provides a lot of powerful functions.

The 2.GCD works as follows:

A specific task that allows the program to queue in parallel, scheduling them to perform tasks on any available processor core, based on the available processing resources. A task can be a function or a block. The bottom of the GCD is still threaded, but this allows the programmer to focus on the details of the implementation.

Advantages of 3.GCD:

GCD is Apple's solution for multi-core parallel computing;

GCD will automatically take advantage of more CPU cores (such as dual-core, quad-core);

GCD automatically manages the life cycle of threads (creating threads, scheduling tasks, destroying threads);

Programmers just need to tell gcd what tasks they want to perform, without having to write any thread management code;

Warm tips:

GCD exists in Libdispatch.dylib This library, this library contains all the GCD, but any iOS program, the default load of the library, in the process of running the program will dynamically load the library, do not need to manually import.

4.GCD use steps and core concepts:

Core probabilities are 2:1) queue: Used to hold task 2) task: What action to take

Use Step 2 steps: 1) customizing Task 2) Determine what you want to do

5.Dispatch Queue (queues):

The FIFO queue in GCD is called the dispatch queue, which guarantees that advanced tasks are executed first, and the dispatch queue is divided into the following three types:

1) Serial dispatch queues (serial queue), while performing only one task (after a task is executed, the next task is performed). Serial queues are typically used to synchronize access to specific resources or data. When you create multiple serial queues, the serial queue is executed concurrently with the serial queue, although they are executed synchronously.

2) Concurren Dispatch queue (concurrent queue), you can perform multiple tasks concurrently (multiple tasks can be executed simultaneously, automatically open multiple threads concurrently to perform tasks, concurrency functions are only valid under asynchronous functions (Dispatch_async)), However, the order in which the executions are completed is random.

3) Main Dispatch queue (home row), which is the globally available serial queue (which executes the task serially in the main thread), which executes the task on the main thread of the application.

6.GCD two ways to perform tasks:

Submit the parameter Block (Task) to the parameter queue (queue) for execution, parameter description:queue: Queued block: Task

(1) Perform the task Dispatch_sync (dispatch_queue_t queue, dispatch_block_t block) in a synchronous manner;

(2) Execute the task Dispatch_async asynchronously (dispatch_queue_t queue, dispatch_block_t block);

7. to prevent the interface from being stuck in processing time-consuming operations, such as reading network data, database reading and writing, we will process these operations in another thread and then notify the main thread to update the interface. Create a global concurrent queue, use dispatch_async to perform the download picture task, and then go back to the main thread to show the picture.

The first way---GCD combines nsthread

 -  (void) viewdidload{    [super viewdidload];      Imagev = [[uiimageview alloc] initwithframe:cgrectmake (100, 100, 100, 100)] ;     [self.view addsubview:imagev];     //Description: Global concurrency Queue Priority # define dispatch_queue_priority_high 2 //  High #define dispatch_queue_priority_default  0 //  Default (Medium) #define  DISPATCH_QUEUE_PRIORITY_LOW  ( -2)  //  low #define  dispatch_queue_priority_background int16_min //  Backstage          //the first parameter global concurrency queue priority, the second parameter is temporarily useless, with 0 can be     dispatch_queue_t queue = dispatch _get_global_queue (dispatch_queue_priority_default, 0);     //use asynchronous Dispatch_async to perform tasks , the first parameter obtains the global concurrent queue, the second parameter block (the task that the queue will perform)     dispatch_async (queue, ^{         //Call to download Image method         [self downimage];    });} 
-(void) downimage{//download picture from the network nsurl *url = [Nsurl urlwithstring:@ "Http://i8.topit.me/8/c1/31/1142319854bdc31c18o.jpg"    ];    Convert a picture to binary data nsdata *imgdata = [NSData Datawithcontentsofurl:url];        Data converted into pictures UIImage *img = [UIImage imagewithdata:imgdata]; Go back to the main thread to set the picture [self performselectoronmainthread: @selector (senderimage:) withobject:img waituntildone:no];} -(void) Senderimage: (UIImage *) image{imagev.image = image;}

The second way---GCD

   dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0),  ^{                 //downloading pictures from the network         nsurl *url = [nsurl urlwithstring:@ "http:/ /i8.topit.me/8/c1/31/1142319854bdc31c18o.jpg "];        //to convert a picture to binary data         NSData *imgData = [NSData  Convert datawithcontentsofurl:url];        //data into pictures          UIImage *img = [UIImage imageWithData:imgData];                 dispatch_async (Dispatch_get_main _queue (),  ^{            //back to the main thread to set the picture display              imagev.image = img;        });     });

Summary: The system provides three concurrent dispatch queues for each application. These three concurrent dispatch queues are global, and they differ only by priority. Because it's global, we don't need to create it. We only need to get the queue by using the function Dispath_get_global_queue, as follows:

dispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default, 0);

In the example above we also use, the system has a serial queue by default Main_queue

dispatch_queue_t Mainqueut = Dispatch_get_main_queue ();

Their code framework is structured as follows:

Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{//Here do some more time-consuming operations, such as requesting data:  Dispatch_async (Dispatch_get_main_queue (), ^{//Here is back to the main thread to update the interface}); });


Introduction and simple use of the iOS development multithreaded article---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.