IOS Multi-threaded programming Grand Central Dispatch (GCD)

Source: Internet
Author: User
Tags gcd

Introduced:

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. It was first released on Mac OS X 10.6, and IOS 4 and above are also available.

Design:

GCD works by allowing programs to queue in parallel to specific tasks, scheduling them to perform tasks on any available processor core, depending 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.

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

Serial

Also known as private dispatch queues, and performs only one task at a time. 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.

Concurrent

Also known as the global dispatch queue, multiple tasks can be executed concurrently, but the order in which the execution is completed is random.

Main Dispatch Queue

It is a globally available serial queue that performs tasks on the main thread of the application.

Let's see how dispatch queue is used

1, the common method Dispatch_async

To prevent the interface from being stuck in processing time-consuming operations, such as reading network data, IO, database reading and writing, we will process these operations in another thread and then notify the main thread to update the interface.

Using GCD to implement this process is simpler than the Nsthread Nsoperation method described earlier. The code framework is structured as follows:

dispatch_async0), ^{          // 耗时的操作          dispatch_async(dispatch_get_main_queue(), ^{              // 更新界面          });      });  

If this is not clear, then we will use the two blog download image as an example, the code is as follows:

 dispatch_async  (Dispatch_ Get_global_queue (Dispatch_queue_priority_default, 0 ), ^{nsurl  * url = [nsurl  urlwithstring:@" http ://avatar.csdn.net/2/c/d/1_totogo2010.jpg "]; NSData * data = [[NSData Alloc]initwithcontentsofurl:url]; uiimage  *image = [[uiimage  alloc] Initwithdata:data]; if  (Data! = nil ) {dispatch_async  (Dispatch_get_main_queue (), ^{self  .imageview  .image  = image; }); } }); 

Run Display:

The code is much simpler than Nsthread nsoperation, and GCD automatically allocates resources on multicore processors based on tasks, optimizing the program.

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 globalQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);   

It's also used here. The system defaults to a serial queue Main_queue

dispatch_queue_t mainQ = dispatch_get_main_queue();    

Although the dispatch queue is a reference-counted object, the above two are global queues without retain or release.

2, the use of Dispatch_group_async

Dispatch_group_async can be used to listen to whether a group of tasks are completed and be notified to perform other operations when completed. This method is useful, for example, you perform three download tasks, and when three tasks are downloaded, you are notified that the interface is complete. Here is an example code:

    dispatch_queue_tQueue = Dispatch_get_global_queue (Dispatch_queue_priority_default,0);      dispatch_group_t group = Dispatch_group_create (); Dispatch_group_async (group, queue, ^{[NsthreadSleepfortimeinterval:1];NSLog(@"Group1");      }); Dispatch_group_async (group, queue, ^{[NsthreadSleepfortimeinterval:2];NSLog(@"Group2");      }); Dispatch_group_async (group, queue, ^{[NsthreadSleepfortimeinterval:3];NSLog(@"Group3");      }); Dispatch_group_notify (Group, Dispatch_get_main_queue (), ^{NSLog(@"UpdateUi");      }); Dispatch_release (group);

Dispatch_group_async is an asynchronous method that you can see when you run the print result:

2012-09-25 16:04:16.737 gcdtest[43328:11303] group1
2012-09-25 16:04:17.738 GCDTEST[43328:12A1B] Group2
2012-09-25 16:04:18.738 gcdtest[43328:13003] Group3
2012-09-25 16:04:18.739 gcdtest[43328:f803] UpdateUi

Each second prints one, and when the third task executes, the UPADTEUI is printed.

3, the use of Dispatch_barrier_async

Dispatch_barrier_async is executed after the execution of the previous task is completed, and the task after it is executed before it executes.

The example code is as follows:

    dispatch_queue_tQueue = Dispatch_queue_create ("GCDTEST.RONGFZH.YC", dispatch_queue_concurrent);Dispatch_async(Queue, ^{[NsthreadSleepfortimeinterval:2];NSLog(@"Dispatch_async1"); });Dispatch_async(Queue, ^{[NsthreadSleepfortimeinterval:4];NSLog(@"Dispatch_async2");      }); Dispatch_barrier_async (Queue, ^{NSLog(@"Dispatch_barrier_async"); [NsthreadSleepfortimeinterval:4]; });Dispatch_async(Queue, ^{[NsthreadSleepfortimeinterval:1];NSLog(@"Dispatch_async3"); });

Printing results:

2012-09-25 16:20:33.967 gcdtest[45547:11203] Dispatch_async1

2012-09-25 16:20:35.967 gcdtest[45547:11303] Dispatch_async2

2012-09-25 16:20:35.967 gcdtest[45547:11303] Dispatch_barrier_async

2012-09-25 16:20:40.970 gcdtest[45547:11303] Dispatch_async3

Each second prints one, and when the third task executes, the UPADTEUI is printed.

3, the use of Dispatch_barrier_async

Dispatch_barrier_async is executed after the execution of the previous task is completed, and the task after it is executed before it executes.

The example code is as follows:

    dispatch_queue_tQueue = Dispatch_queue_create ("GCDTEST.RONGFZH.YC", dispatch_queue_concurrent);Dispatch_async(Queue, ^{[NsthreadSleepfortimeinterval:2];NSLog(@"Dispatch_async1"); });Dispatch_async(Queue, ^{[NsthreadSleepfortimeinterval:4];NSLog(@"Dispatch_async2");      }); Dispatch_barrier_async (Queue, ^{NSLog(@"Dispatch_barrier_async"); [NsthreadSleepfortimeinterval:4]; });Dispatch_async(Queue, ^{[NsthreadSleepfortimeinterval:1];NSLog(@"Dispatch_async3"); });

Printing results:

2012-09-25 16:20:33.967 gcdtest[45547:11203] Dispatch_async1

2012-09-25 16:20:35.967 gcdtest[45547:11303] Dispatch_async2

2012-09-25 16:20:35.967 gcdtest[45547:11303] Dispatch_barrier_async

2012-09-25 16:20:40.970 gcdtest[45547:11303] Dispatch_async3

Note that the execution time can be seen in the order of execution as described above.

4, Dispatch_apply

Executes a code fragment n times.

dispatch_apply(5index) {    // 执行5次});

Example code used in this article: http://download.csdn.net/detail/totogo2010/4596471

GCD There are many other uses, you can refer to the official documentation

The documentation for reference is also: Http://en.wikipedia.org/wiki/Grand_Central_Dispatch

Top two multi-line Cheng Bowen: The use of Nsthread for iOS multithreaded programming
The use of nsoperation and Nsoperationqueue for iOS multithreaded programming

Copyright statement: This article by http://blog.csdn.net/totogo2010/Original, welcome reprint share. Please respect the author Labor, reproduced when the statement and the author of the blog link, thank you!

Jongfangzhi (http://www.cnblogs.com/stoic/)

This article follows "Attribution-non-commercial use-consistent" authoring public agreement

IOS Multi-threaded programming Grand Central Dispatch (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.