Introduction and use of Grand Central Dispatch (GCD) for iOS multi-thread programming

Source: Internet
Author: User

Introduction and use of Grand Central Dispatch (GCD) for iOS multi-thread programming
Introduction:

Grand Central Dispatch (GCD) is a technology developed by Apple to optimize applications that support multi-core processors and other systems of Symmetric Multi-processing systems. This is based on the Thread Pool Mode for concurrent task execution. It is released on Mac OS X 10.6 For the first time, and is also available for iOS 4 and later versions.

Design:

GCD works as follows: allows programs to queue specific tasks in parallel and schedule them to execute tasks on any available processor core based on available processing resources.

A task can be a function or a block. The underlying layer of GCD is still implemented using threads, but this allows programmers to ignore implementation details.

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

Serial

It is also called private dispatch queues and only executes one task at the same time. Serial queue is usually used to synchronously access specific resources or data. When you create multiple Serial queue, although they are executed simultaneously, the Serial queue and Serial queue are executed concurrently.

Concurrent

It is also called global dispatch queue. It can execute multiple tasks concurrently, but the execution order is random.

Main dispatch queue

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

Let's see how to use dispatch queue.

1. Common Methods: dispatch_async

To prevent the interface from getting stuck when processing time-consuming operations, such as reading network data, I/O, and database reads and writes, 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 structure is as follows:

 

  1. Dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
  2. // Time-consuming operations
  3. Dispatch_async (dispatch_get_main_queue (), ^ {
  4. // Update the interface
  5. });
  6. }); If this is not clear, we will use the download images from the two blogs as an example. The Code is as follows:

     

     

    1. Dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
    2. NSURL * url = [NSURL URLWithString: @ http://avatar.csdn.net/2/c/d/?togo2010.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:

      Is the code much simpler than NSThread NSOperation, and GCD automatically allocates resources and optimizes programs on multi-core processors based on tasks.

      The system provides three concurrent dispatch queues for each application. These three concurrent scheduling queues are global, and they only have different priorities. Because it is global, we do not need to create it. We only need to use the dispath_get_global_queue function to get the queue, as shown below:

       

      1. Dispatch_queue_t globalQ = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 );

         

        The system has a serial queue main_queue by default.

         

        1. Dispatch_queue_t mainQ = dispatch_get_main_queue ();

           

          Although dispatch queue is a reference counting object, both of the above are global queues without retain or release.

          2. Use dispatch_group_async

          Dispatch_group_async can be used to monitor whether a group of tasks are completed, and other operations are notified after completion. This method is very useful. For example, if you execute three download tasks, you will be notified after all the three download tasks are completed. The following is an example code:

           

          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_policy (group, dispatch_get_main_queue (), ^ {
          16. NSLog (@ updateUi );
          17. });
          18. Dispatch_release (group); dispatch_group_async is an asynchronous method. The printed result is displayed after running:

             

            16:04:16. 737 gcdTest [43328: 11303] group1
            16:04:17. 738 gcdTest [43328: 12a1b] group2
            16:04:18. 738 gcdTest [43328: 13003] group3
            16:04:18. 739 gcdTest [43328: f803] updateUi

            Print one task per second. When the third task is executed, the upadteUi is printed.

             

            3. Use dispatch_barrier_async

            Dispatch_barrier_async is executed only after the previous task is executed, and the subsequent task will be executed only after it is executed.

            The sample code is as follows:

             

            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. });
            15. Dispatch_async (queue, ^ {
            16. [NSThread sleepForTimeInterval: 1];
            17. NSLog (@ dispatch_async3 );
            18. });
              Print result:

               

              16:20:33. 967 gcdTest [45547: 11203] dispatch_async1

              16:20:35. 967 gcdTest [45547: 11303] dispatch_async2

              16:20:35. 967 gcdTest [45547: 11303] dispatch_barrier_async

              16:20:40. 970 gcdTest [45547: 11303] dispatch_async3

              Pay attention to the execution time. You can see the execution sequence as described above. 4. dispatch_apply

              Execute a code snippet N times.
              Dispatch_apply (5, globalQ, ^ (size_t index ){
              // Execute 5 times
              });

               

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.