Introduction and use of the Grand Central Dispatch (GCD) for iOS multithreaded programming

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:

[CPP]View Plaincopy < param name= "wmode" value= "Transparent" >
    1. Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{
    2. //time-consuming Operation
    3. Dispatch_async (Dispatch_get_main_queue (), ^{
    4. //Update interface
    5. });
    6. });

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

[CPP]View Plaincopy
  1. Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{
  2. Nsurl * url = [nsurl urlwithstring:@"Http://avatar.csdn.net/2/C/D/1_totogo2010.jpg"];
  3. NSData * data = [[NSData Alloc]initwithcontentsofurl:url];
  4. UIImage *image = [[UIImage alloc]initwithdata:data];
  5. if (data! = nil) {
  6. Dispatch_async (Dispatch_get_main_queue (), ^{
  7. Self.imageView.image = image;
  8. });
  9. }
  10. });

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:

[CPP]View Plaincopy
    1. 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

[CPP]View Plaincopy
    1. 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:

[CPP]View Plaincopy
  1. dispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default, 0);
  2. dispatch_group_t group = Dispatch_group_create ();
  3. Dispatch_group_async (group, queue, ^{
  4. [Nsthread sleepfortimeinterval:1];
  5. NSLog (@"group1");
  6. });
  7. Dispatch_group_async (group, queue, ^{
  8. [Nsthread Sleepfortimeinterval:2];
  9. NSLog (@"group2");
  10. });
  11. Dispatch_group_async (group, queue, ^{
  12. [Nsthread Sleepfortimeinterval:3];
  13. NSLog (@"Group3");
  14. });
  15. Dispatch_group_notify (Group, Dispatch_get_main_queue (), ^{
  16. NSLog (@"updateUi");
  17. });
  18. 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:

[CPP]View Plaincopy
  1. dispatch_queue_t queue = dispatch_queue_create ("Gcdtest.rongfzh.yc", dispatch_queue_concurrent);
  2. Dispatch_async (Queue, ^{
  3. [Nsthread Sleepfortimeinterval:2];
  4. NSLog (@"dispatch_async1");
  5. });
  6. Dispatch_async (Queue, ^{
  7. [Nsthread Sleepfortimeinterval:4];
  8. NSLog (@"DISPATCH_ASYNC2");
  9. });
  10. Dispatch_barrier_async (Queue, ^{
  11. NSLog (@"Dispatch_barrier_async");
  12. [Nsthread Sleepfortimeinterval:4];
  13. });
  14. Dispatch_async (Queue, ^{
  15. [Nsthread sleepfortimeinterval:1];
  16. NSLog (@"dispatch_async3");
  17. });


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 (5, Globalq, ^ (size_t index) {
Performed 5 times
});

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!

Introduction and use of the Grand Central Dispatch (GCD) for iOS multithreaded programming

Related Article

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.