Use of iOS multi-thread GCD and ios multi-thread gcd

Source: Internet
Author: User

Use of iOS multi-thread GCD and ios multi-thread gcd

In iOS development, we often use multithreading for time-consuming operations. Grand Central Dispatch (GCD) is a multi-core programming solution developed by Apple. You only need to define the task to be executed and add it to the appropriate scheduling queue (dispatch queue ). GCD is responsible for creating threads and scheduling your tasks. The system provides thread management directly.

I. queue: Basic concepts:

1. an important concept of GCD is queue. Its core concept is to split long-running tasks into multiple work units and add these units to dispath queue, the system will manage these dispath queue for us and execute work units on multiple threads. We do not need to directly start and manage background threads.

2. The system provides many predefined dispath queue, including the dispath queue that can ensure that work is always executed on the main thread. You can also create your own dispath queue, and you can create any number of dispath queue. The dispath queue of GCD strictly follows the FIFO (first-in-first-out) principle. The unit of work added to the dispath queue is always started in the order that the dispath queue is added.

3. The dispatch queue executes tasks in a serial or concurrent manner in the FIFO order.

1> the serial dispatch queue can only execute one task at a time. After the current task is completed, columns are started and the next task is started.

2> concurrent dispatch queue starts as many concurrent tasks as possible

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.

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.

 

Ii. 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 });
3. Example of a GCD application:

Now a time-consuming operation starts to work from start working, uses multithreading, and then displays the result.

Declare controls:

@property (weak, nonatomic) IBOutlet UIButton *startButton;@property (weak, nonatomic) IBOutlet UITextView *resultsTextView;@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *spinner;

Click startButton to start execution.

-(IBAction) doWork :( id) sender {NSDate * startTime = [NSDate date]; self. startButton. enabled = NO; [self. spinner startAnimating]; // dispatch_get_global_queue (): captures a global queue that already exists and is always available. This function accepts two parameters: the first one specifies the priority, and the second one is not currently in use, always 0. dispatch_queue_t queue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // transmits the queue and the code block following it to the dispatch_async () function, and GCD then obtains the entire program block, and pass it to a background thread. The program block will execute one step here. Dispatch_async (queue, ^ {NSString * fetchedData = [self encoding]; NSString * processedData = [self processData: fetchedData]; _ block NSString * firstResult; _ block NSString * secondResult; dispatch_group_t group = dispatch_group_create (); // The dispatch_group_async () function sets all program blocks asynchronously distributed to loose and runs as soon as possible. Groups (group, queue, ^ {firstResult = [self calculateFirstResult: processedData] ;}); groups (group, queue, ^ {secondResult = [self calculateSecondResult: processedData];}); dispatch_group_policy (group, queue, ^ {NSString * resultsSummary = [NSString stringWithFormat: @ "First: [% @] \ nSecond: [% @]", firstResult, secondResult]; // The queue returned by the dispatch_get_main_queue function. This function always provides a specific queue on the thread and runs the program block dispatch_async (dispatch_get_main_queue (), ^ {self. resultsTextView. text = resultsSummary; self. startButton. enabled = YES; [self. spinner stopAnimating];}); NSDate * endTime = [NSDate date]; NSLog (@ "Completed in % f seconds", [endTime timeIntervalSinceDate: startTime]) ;}) ;}

Other methods:

// Simulate obtaining data from the server-(NSString *) fetchSomethingFromServer {[NSThread sleepForTimeInterval: 1]; return @ "Hi there" ;}- (NSString *) processData :( NSString *) data {[NSThread sleepForTimeInterval: 2]; return [data uppercaseString];}-(NSString *) rows :( NSString *) data {[NSThread sleepForTimeInterval: 3]; return [NSString stringWithFormat: @ "Number of chars: % lu", (unsigned long) [data length];}-(NSString *) calculateSecondResult :( NSString *) data {[NSThread sleepForTimeInterval: 4]; return [data stringByReplacingOccurrencesOfString: @ "E" withString: @ "e"];}

Result:

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

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.