Use of multithreaded GCD

Source: Internet
Author: User
Tags gcd

Gcd--grand Central Dispatch is a C-based framework that makes full use of multicore and is also an official recommended multithreaded technology by Apple.

GCD is a multi-core programming solution developed by Apple. Ios4.0+ can be used as an alternative to Nsthread,nsoperation's efficient and powerful technology, GCD is based on the C language

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 (create threads, schedule tasks, destroy threads)

Programmers just need to tell gcd what they want to do, don't need to write any thread management code multithreading inside the concept of a lot of things are difficult to remember, so be sure to understand well. or through the code, in the brush up. The same code is written several times, although sometimes very dull, but each time there will be different experience and understanding. Get Up! In Viewcontroller:
1 #import "ViewController.h"2 3 @interfaceViewcontroller ()4 5 @end6 7 @implementationViewcontroller8 9 /*Ten //write before you go to brush up.  One use of GCD: A One: Queue - 1. Serial queue: The task that is added to the queue is a single execution - 2. Concurrent (ROW) Queues: Tasks added to the queue are multiple simultaneous executions the 3. Home column: The tasks inside are performed on the main thread.  - 4. Global queue: Parallel (outgoing) queue -   - Two: synchronous, asynchronous + 1, synchronization: Need to wait for the later task, will not open a new thread, will be directly using the current thread -   + 2, Async: Do not need to wait for the later task, will open a new thread A  */ at  -- (void) Viewdidload { - [Super Viewdidload]; -      -     /*---------Create a concurrent queue---------*/ -  in     //1. Create a parallel queue -dispatch_queue_t queue1 = Dispatch_queue_create ("queue1", dispatch_queue_concurrent); to      +     //2. Get the global queue (parallel queue) -     /*Priority < #long identifier#> the Dispatch_queue_priority_high * Dispatch_queue_priority_default $ Dispatch_queue_priority_lowPanax Notoginseng Dispatch_queue_priority_background -      */ the      +dispatch_queue_t queue2 = Dispatch_get_global_queue (Dispatch_queue_priority_default,0); A      the     //(1) Adding an asynchronous task in a concurrent queue +  -Dispatch_async (queue2, ^{ $      $                    for(inti =0; I < -; i + +) { -                  -NSLog (@"1---------1"); the             } -         Wuyi          the     }); -      WuDispatch_async (queue2, ^{ -          About          $              for(inti =0; I < -; i + +) { -                  -NSLog (@"2---------2"); -             } A          +          the});

Printing results:

By printing the results we can see: (1) Concurrent queue Asynchronous Add a task will open multiple threads, the execution order is not sequential (at the same time) read the asynchronous Add queue, let us look at the synchronization of concurrent queue add:

1Dispatch_sync (queue2, ^{2     3 @autoreleasepool {4              for(inti =0; I < -; i + +) {5                 6NSLog (@"1---------1");7             }8         }9     });Ten      One      ADispatch_sync (queue2, ^{ -          - @autoreleasepool { the              for(inti =0; I < -; i + +) { -                  -NSLog (@"2---------2"); -             } +         } -});

This printout is believed to be needless to say, we all know it must be done first 1 in execution 2

In fact, the implementation of a good answer, the key is at this time the task is done in that thread, I believe if you add to the concept of synchronization is very clear, you can answer right, there is no mistake. These tasks are done in the main thread. is not done in the queue2. Let's take a look at the picture. Through the above analysis we can see: (1) in the concurrent queue to add tasks, not open new threads, will directly use the current thread, (2) and we added the task is added to the main thread.  is not a queue2 of superficial phenomena. After reading the concurrent (row) queue, let's take a look at the serial queue.
1     /*---------Create a serial----------*/2     3dispatch_queue_t queue = Dispatch_queue_create ("Queue3", dispatch_queue_serial);4     5     //to add tasks asynchronously to a serial queue6Dispatch_async (Queue, ^{7     8          for(intI=0; i< -; i++) {9NSLog (@"?? ... .. i:%d", i);Ten         } One  A     }); -      -Dispatch_async (Queue, ^{ the      -          for(intI=0; i< -; i++) { -NSLog (@"?? ... .. i:%d", i); -         } +  -});

Printing results:

Although it is an asynchronous add task, the queue is a serial queue, so the pig is executed before the dog is executed.

If we were to add a for loop under the dog's for Talk again in Viewdidload, can you imagine the result?

1      for (int i=0; i<; i++) {2         NSLog (@ "?? ..... i:%d", i); 3     }

Printing results:

It is not difficult to see that cats are carried out at the same time as (dogs and pigs). and (pigs and dogs) are pigs performed first, dogs in execution. For example, a pig and a dog lined up, and the cat lined up for a team. Continue the Introduction:

To add a task to a serial queue synchronously

    Dispatch_sync (queue, ^{for                (int i=0; i<50; i++) {            NSLog (@ "?? ..... i:%d ", i);        }    );        Dispatch_sync (queue, ^{for            (int i=0; i<100; i++) {            NSLog (@ "?? ..... i:%d ", i);        }            );        for (int i=0; i<100; i++) {        NSLog (@ "?? ..... i:%d ", i);    }

The results of the operation are no doubt. Dog-----"Cat----------" pig; always remember to add tasks synchronously, without opening new threads, and using the current thread directly. Then be sure that these three tasks are also in the current main thread.

Well, there's one important thing about this, and that's the deadlock.

Let's take a look.

Get the Home column:

    dispatch_queue_t mainqueue = Dispatch_get_main_queue ();

Assigning tasks:

1NSLog (@"mission started!!! ");2     //Synchronizing Add Tasks3Dispatch_sync (Mainqueue, ^{4     5NSLog (@"Task Add");6         7     });8     9NSLog (@"End");

There is no doubt that the first print is definitely the first line of "task begins!!! ", then go to the third line of code, because it is a block so the fifth line of code to be executed at the end of the Nineth line after the print execution (block callback), and because it is a synchronous add task, so the nineth line of code in the above task can be completed before the start. So the compiler hesitated not to know which one to execute. can cause deadlocks.

Printing results:

Summary: (1) When using the primary queue, it is absolutely not possible to add tasks synchronously in the main queue, resulting in deadlocks.

(2) Concurrent queue: synchronous addition does not open a new thread, and asynchronous addition turns on multiple threads.

(3) Serial queue: synchronous addition does not open a new thread, and an asynchronous addition opens a thread.

(4) Draw conclusions from (2) and (3) to add tasks synchronously, without the ability to open threads. The number of threads that an asynchronous add task opens is determined by the current queue, the serial queue opens a thread, and the parallel queue opens multiple lines.

Use of multithreaded 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.