Multi-thread GCD for iOS crazy explanation

Source: Internet
Author: User
Tags call back

Multi-thread GCD for iOS crazy explanation

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

Dispatch queue is divided into the following three types:

1) The Main queue running in the Main thread is obtained through dispatch_get_main_queue.


/*!* @function dispatch_get_main_queue** @abstract* Returns the default queue that is bound to the main thread.** @discussion* In order to invoke blocks submitted to the main queue, the application must* call dispatch_main(), NSApplicationMain(), or use a CFRunLoop on the main* thread.** @result* Returns the main queue. This queue is created automatically on behalf of* the main thread before main() is called.*/__OSX_AVAILABLE_STARTING(__MAC_10_6,__IPHONE_4_0)DISPATCH_EXPORT struct dispatch_queue_s _dispatch_main_q;#define dispatch_get_main_queue() \DISPATCH_GLOBAL_OBJECT(dispatch_queue_t, _dispatch_main_q)

We can see that dispatch_get_main_queue is also a kind of dispatch_queue_t.

2) The global dispatch queue of the parallel queue is obtained through dispatch_get_global_queue. The system creates three dispatch queue with different priorities. The execution sequence of the parallel queue is the same as that of the queue.

3) serial queue serial queues is generally used for sequential synchronous access. You can create any number of serial queues, and each serial queue is concurrent.

The serial queue is useful when you want to execute tasks in a specific order. The serial queue only executes one task at the same time. We can use serial queues instead of locks to protect shared data. Unlike locks, a serial queue ensures that tasks are executed in a predictable order.

Serial queues is created through dispatch_queue_create. You can use the dispatch_retain and dispatch_release functions to increase or decrease the reference count.

GCD usage:


// Background execution: dispatch_async (dispatch_get_global_queue (0, 0), ^ {// something}); // main thread execution: dispatch_async (dispatch_get_main_queue (), ^ {// something}); // One-time execution: static dispatch_once_t onceToken; dispatch_once (& onceToken, ^ {// code to be executed once }); // 2 seconds delayed execution: double delayInSeconds = 2.0; interval popTime = dispatch_time (DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); dispatch_after (popTime, interval (), ^ (void) {// code to be executed on the main queue after delay}); // custom queue urls_queue = dispatch_queue_create ("blog.devtang.com", NULL); dispatch_async (urls_queue, ^ {// your code}); dispatch_release (urls_queue); // merge the summary result dispatch_group_t group = dispatch_group_create (); dispatch_group_async (group, limit (0, 0 ), ^ {// thread 1 for parallel execution}); dispatch_group_async (group, dispatch_get_global_queue (), ^ {// thread 2 for parallel execution}); dispatch_group_notify (group, dispatch_get_global_queue (0, 0), ^ {// Summary Result });

Example of a GCD application:


    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{        NSURL * url = [NSURL URLWithString:@"http://www.baidu.com"];        NSError * error;        NSString * data = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];        if (data != nil) {            dispatch_async(dispatch_get_main_queue(), ^{                NSLog(@"call back, the data is: %@", data);            });        } else {            NSLog(@"error when download:%@", error);        }    });

Another use of GCD is to allow programs to run for a long time in the background.

When GCD is not used, when the app is exited by pressing the home key, the app only needs 5 seconds to save or clear resources. However, after using GCD, the app can run for up to 10 minutes in the background for a long time. This time can be used to clear the local cache and send statistics.

The sample code for long-running programs in the background is as follows:


// AppDelegate. hfile @ property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask; // AppDelegate. m file-(void) applicationDidEnterBackground :( UIApplication *) application {[self beingBackgroundUpdateTask]; // Add the code you need to run for a long time here [self endBackgroundUpdateTask];}-(void) beingBackgroundUpdateTask {self. backgroundUpdateTask = [[UIApplication sharedApplication] usage: ^ {[self endBackgroundUpdateTask] ;}];}-(void) usage {[[UIApplication sharedApplication] endBackgroundTask: self. backgroundUpdateTask]; self. backgroundUpdateTask = UIBackgroundTaskInvalid ;}

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.