iOS Network multithreading-GCD

Source: Internet
Author: User
Tags call back

Grand Central Dispatch (GCD) is a solution for multi-core programming developed by Apple.

The dispatch queue is divided into the following three types:

1) Run the main queue in the main thread, obtained through Dispatch_get_main_queue.

/* !* @function dispatch_get_main_queue** @abstract * Returns The default queue that's bound to the main thread.** @discu ssion* in order to invoke blocks submitted to the main queue, the application must* call Dispatch_main (), Nsapplicationmai N (), or use a cfrunloop the main* thread.** @result * Returns the main queue. This queue was created automatically on behalf of* the main thread before main () is called. */  struct  dispatch_queue_s _dispatch_main_q; #define dispatch_get_main_queue () \dispatch_global_object (dispatch_queue_t, _dispatch_main_q)

As can be seen, Dispatch_get_main_queue is also a kind of dispatch_queue_t.

2) Parallel queue Global dispatch queue, obtained by Dispatch_get_global_queue, creates three different priority dispatch queues by the system. Parallel queues are executed in the same order as they join the queue.

3) Serial queue serial queues is typically used to synchronize access sequentially, creating any number of serial queues that are concurrent between each serial queue.

Serial queues are useful when you want tasks to execute in a particular order. A serial queue performs only one task at a time. We can use serial queues instead of locks to protect shared data. Unlike locks, a serial queue guarantees that the task executes in a predictable order.

Serial queues is created through dispatch_queue_create and can be used to increase or decrease the reference count using function Dispatch_retain and dispatch_release.

usage of GCD :

 //Background execution:Dispatch_async (Dispatch_get_global_queue (0,0), ^{      //something });
//main thread Execution:Dispatch_async (Dispatch_get_main_queue (), ^{ //something });
//Disposable Execution: Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{ //code to be executed once });
//delay of 2 seconds execution: DoubleDelayinseconds =2.0; dispatch_time_t Poptime= Dispatch_time (Dispatch_time_now, Delayinseconds *nsec_per_sec); Dispatch_after (Poptime, Dispatch_get_main_queue (),^(void){ //Code to is executed on the main queue after delay });
//Custom dispatch_queue_tdispatch_queue_t Urls_queue = Dispatch_queue_create ("blog.devtang.com", NULL); Dispatch_async (Urls_queue,^{//Your code }); Dispatch_release (Urls_queue);
//Merge Summary Resultsdispatch_group_t Group =dispatch_group_create (); Dispatch_group_async (Group, Dispatch_get_global_queue (0,0), ^{ //thread one in parallel execution }); Dispatch_group_async (Group, Dispatch_get_global_queue (0,0), ^{ //threads executed in parallel two }); Dispatch_group_notify (Group, Dispatch_get_global_queue (0,0), ^{ //Summary Results});

An example of applying GCD:

    0), ^{        * url = [Nsurl urlwithstring:@ "http://www.baidu.com"];        * error;         * data = [NSString stringwithcontentsofurl:url encoding:nsutf8stringencoding error:&error];         if (data = nil) {            ^{                NSLog@ "call back, the data is:%@"  , data);            });         Else {            NSLog (@ "error when download:%@", error);        }    );

Another use of GCD is to allow programs to run longer in the background.

When you do not use GCD, when the app is left on the home button, the app only has a maximum of 5 seconds to do some saving or cleanup work. But after using GCD, the app has a maximum of 10 minutes to run in the background for a long time. This time can be used to clean up the local cache, send statistics and other work.

The sample code that lets the program run long in the background is as follows:

// AppDelegate.h File @property (Assign, nonatomic) Uibackgroundtaskidentifier backgroundupdatetask; // appdelegate.m file -(void) Applicationdidenterbackground: (uiapplication *) application{    [ Self beingbackgroundupdatetask];     // Add the code that you need to run long     [self endbackgroundupdatetask];} -(void) beingbackgroundupdatetask{    = [[UIApplication sharedapplication] beginbackgroundtaskwithexpirationhandler:^{        [self endbackgroundupdatetask];    }];} -(void) endbackgroundupdatetask{    [[UIApplication sharedapplication] Endbackgroundtask: Self.backgroundupdatetask];     = uibackgroundtaskinvalid;}

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.