iOS Development: GCD multithreading

Source: Internet
Author: User

iOS has three multithreaded programming techniques, namely Nsthread,cocoa nsoperation and GCD,GCD full-name Grand Central Dispatch, a multi-core programming solution developed by Apple, that can be used after the start of iOS4.0. GCD is an alternative to Nsthread, Nsoperationqueue, nsinvocationoperation and other technologies are very efficient and powerful technology, and its use than the previous two more simple and convenient, today mainly to introduce you about the use of GCD.

GCD works by allowing programs to queue in parallel to specific tasks, scheduling them to perform tasks on any available processor core, depending on the available processing resources. A task can be a function or a block of statements, GCD is still implemented with threads, but this allows ordinary developers to focus on the details of their implementation, and queues in GCD are called dispatch queue.

  The Dispatch queue is divided into three types:

1. Serial Dispatch queue: Linear execution of Thread queues, followed by FIFO (first first out) principle;

2. Concurrent Dispatch queue: Concurrent execution of thread queues, the number of concurrent executions depends on the current state;

3. Main Dispatch Queue: Perform tasks on the main thread of the application.

Let 's look at a few common methods:

 1.dispatch_async

Sometimes avoid the interface in processing time-consuming operation, such as initiating network requests, downloading data, caching images, etc., we need to handle these operations in another thread, after these operations are completed, then notify the main thread update interface, see the following code

Dispatch_async (Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{        //time-consuming Operationnsdate* date =[NSDate Date]; NSLog (@"------%@", date); Nsurl* URL = [Nsurl urlwithstring:@"http://d.hiphotos.baidu.com/image/pic/item/0823dd54564e9258ca2f34e79e82d158ccbf4e9b.jpg"]; NSData* data =[[NSData Alloc]initwithcontentsofurl:url]; UIImage*image =[[UIImage Alloc]initwithdata:data]; [Nsthread sleepfortimeinterval:4];//in order to reflect the characteristics of multithreading here set a delay        if(Data! =Nil) {Dispatch_async (Dispatch_get_main_queue (),^{                //result Processinguiimageview* ImageView =[[Uiimageview alloc]initwithimage:image]; Imageview.frame=[UIScreen mainscreen].bounds;                [Self.view Addsubview:imageview]; NSDate* Date =[NSDate Date]; NSLog (@"------%@", date);        }); }    });

We do the action of downloading the picture in a thread (in order to reflect the role of multithreading, we set a delay here) and then in another line thread to show the picture, look at the results of the operation.

The system provides a queue for each application, so it is generally not necessary for us to create it manually, we just need to get the queue through the function.

// get main Dispatch Queuedispatch_queue_t maindispatchqueue = dispatch_get_main_queue (); // get global Dispatch Queue 0);
2, Dispatch_group_async

  Dispatch_group_async can implement a set of tasks to listen to, after a series of tasks are completed before other operations.

Take a look at some examples:

dispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default,0); dispatch_group_t Group=dispatch_group_create (); Dispatch_group_async (group, queue,^{[Nsthread sleepfortimeinterval:1]; NSLog (@"Thread 1");    }); Dispatch_group_async (group, queue,^{[Nsthread sleepfortimeinterval:5]; NSLog (@"Thread 2");    }); Dispatch_group_async (group, queue,^{[Nsthread sleepfortimeinterval:3]; NSLog (@"Thread 3"); });
The Dispatch_group_notify function is used to specify an additional block that executes dispatch_group_notify after all tasks in group are completed (group, Dispatch_get_main_ Queue (),^{NSLog (@"Update Action"); });

As can be seen from the results, the update operation is performed after all 3 threads have finished executing

3, Dispatch_barrier_async

Dispatch_barrier_async is executed after the execution of the previous task is completed, and the task after it is executed before it executes.

dispatch_queue_t queue = Dispatch_queue_create ("Gcdtest2", dispatch_queue_concurrent); Dispatch_async (Queue,^{[Nsthread sleepfortimeinterval:1]; NSLog (@"Thread 1");    }); Dispatch_async (Queue,^{[Nsthread sleepfortimeinterval:5]; NSLog (@"Thread 2");    }); Dispatch_barrier_async (Queue,^{NSLog (@"Barrier Execution"); [Nsthread sleepfortimeinterval:5];    }); Dispatch_async (Queue,^{[Nsthread sleepfortimeinterval:1]; NSLog (@"Thread 4"); });

  

iOS Development: GCD multithreading

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.