ios--Multi-thread GCD

Source: Internet
Author: User
Tags gcd

GCD first, Brief introduction 1. What is GCD?
    • The full name is Grand Central Dispatch, which translates as "the backbone scheduler"
    • Pure C language, provides a lot of powerful functions
Advantages of 2.GCD
    • 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 tasks they want to perform, without having to write any thread management code
3. Tips
    • (1) GCD exists in Libdispatch.dylib This library, this library contains all the GCD, but any iOS program, the default load of the library, in the process of running the program will dynamically load the library, do not need to manually import.
    • (2) GCD is a pure C language, so when we write GCD related code, we face the function, not the method.
    • (3) Most of the functions in GCD start with dispatch.
Ii. tasks and Queues 1. There are 2 core concepts in GCD
    • (1) Task: what action to perform
    • (2) Queue: for storing tasks
2 Steps for 2.GCD use
    • (1) Custom tasks
    • (2) Determine what you want to do
Adding tasks to the queue, GCD automatically takes the tasks from the queue and puts them in the corresponding thread 提示:The removal of a task follows the FIFO principle of the queue: first-in, last-out, third, perform task 1. There are 2 functions for performing tasks in GCD 说明:The right parameter (Task) is submitted to the left parameter (queue) for execution. (1) Perform tasks in a synchronous manner
    • Dispatch_sync (dispatch_queue_t queue, dispatch_block_t block);
Parameter description:
    • Queue: Queues
    • Block: Task
(2) Perform the task in an asynchronous manner
    • Dispatch_async (dispatch_queue_t queue, dispatch_block_t block);
2. The difference between synchronous and asynchronous
    • Synchronization: Executing in the current thread不具备开启新线程的能力
    • Async: Executing in another thread具备开启新线程的能力
Iv. queues
    • Create a queue
      • Dispatch_queue_create (const char *label, dispatch_queue_attr_t attr)
      • The first parameter is the name of the queue
      • The second parameter is a queue type
        • dispatch_queue_concurrent/Concurrent Queues
        • dispatch_queue_serial/serial queue, default NULL1. Type of queue

The GCD queue can be divided into 2 major types

(1) Concurrent queues (Concurrent Dispatch queue)
    • You can have multiple tasks concurrently ( 同时 ) execute (automatically open multiple threads concurrently to perform tasks) concurrency function only 异步(dispatch_async) works under functions
(2) Serial queuing (Serial Dispatch queue)
    • Let the task execute one after the other (once a task has finished executing, then the next task is performed)
2. Supplementary instructions

easy to confuse terminology 同步 异步 并发串行

    • Synchronous and asynchronous determine whether to open a new thread

      • Synchronous: Performs a task in the current thread without the ability to open a new thread
      • Async: Perform a task in a new thread with the ability to open a new thread
    • Concurrency and serialization determine how tasks are executed

      • Concurrency: Multiple tasks concurrently (concurrently) executed
      • Serial: Once a task is completed, the next task is performed
3. Concurrent queues
    • Dispatch_queue_concurrent

The GCD default already provides a global concurrency queue for the entire app to use, without the need to manually create

    • Using the Dispatch_get_global_queue function to obtain a global concurrency queue
dispatch_queue_t dispatch_get_global_queue(dispatch_queue_priority_t priority,unsigned long flags); // 第二个参数暂时无用,用0即可//示例://这个参数是留给以后用的,暂时用不上,传个0。//第一个参数为优先级,这里选择默认的。获取一个全局的默认优先级的并发队列。dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // 获得全局并发队列
First parameter description: iOS8 before global concurrency queue priority/ios8 later on behalf of quality of service iOS 8
#define DISPATCH_QUEUE_PRIORITY_HIGH 2 // 高#define DISPATCH_QUEUE_PRIORITY_DEFAULT 0 // 默认(中)#define DISPATCH_QUEUE_PRIORITY_LOW (-2) // 低#define DISPATCH_QUEUE_PRIORITY_BACKGROUND INT16_MIN(-32768) // 后台
Starting with iOS 8, the values are hexadecimal
 *  - QOS_CLASS_USER_INTERACTIVE (用户交互,用于迫切的想执行任务,不要在这种服务质量下做耗时的操作) *  - QOS_CLASS_USER_INITIATED 用户需要 *  - QOS_CLASS_DEFAULT 默认(重置队列) *  - QOS_CLASS_UTILITY  实用工具(耗时的操作放在这里) *  - QOS_CLASS_BACKGROUND 后台 *  - QOS_CLASS_UNSPECIFIED 没有设置任何的优先级
4. Serial Queue

There are 2 ways to get serial in GCD

(1) Creating a serial queue using the Dispatch_queue_create function
dispatch_queue_t  dispatch_queue_create(const char *label,  dispatch_queue_attr_t attr); // 队列名称, 队列属性,一般用NULL即可,默认创建的时串行//示例:dispatch_queue_t queue = dispatch_queue_create("wendingding", NULL); // 创建dispatch_release(queue); // 非ARC需要释放手动创建的队列
(2) using the primary queue (the queue associated with the mainline threads)

Perform a synchronization task in the main queue, a dead loop occurs and the task cannot be executed down

    • The primary queue is a special serial queue that comes with the GCD, and the tasks placed in the master queue are placed in the main thread to execute
    • Use Dispatch_get_main_queue () to get the home row
    • Refreshes the UI in the main thread, although it is sometimes possible to manipulate the UI in a child thread, but do not do so because sometimes it is impossible to manipulate in a child thread
//示例:dispatch_queue_t queue = dispatch_get_main_queue();
5. Execution effect of various queues

V. Common methods of GCD 1. Deferred execution ① Introduction iOS Common latency execution There are 2 ways a. Using Nstimer method
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:NO];//2秒后再调用self的run方法
B. Methods for calling NSObject
    • Call the self's Run method after 2 seconds
[self performSelector:@selector(run) withObject:nil afterDelay:2.0];//此方法的原理是利用NSTimer
C. Using the GCD function
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{     2秒后异步执行这里的代码...});
② description

The first to second method, which is called on that thread, is where run executes (the current thread), usually the main thread. [Self performselector: @selector (Run) Withobject:nil afterdelay:3.0];

2. Disposable code
    • Implementing one-time code
    • The entire program runs, only once.
static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{    // 只执行1次的代码(这里面默认是线程安全的)});
3. Super Traversal
    • Parallel execution traversal
     for (int i = 0; i < 10; i++) {     NSLog(@"%@, %i",[NSThread currentThread] , i); } /* 第一个参数: 需要执行几次任务 第二个参数: 队列 第三个参数: 当前被执行到得任务的索引 */ dispatch_apply(10, dispatch_get_global_queue(0, 0), ^(size_t index) { NSLog(@"%@, %zd",[NSThread currentThread] , index); });
4. Guardrail
    • To perform all previous tasks before executing barrier, you must meet two conditions
        1. All tasks are in the same queue
        1. The queue cannot be a global parallel queue, it must be a queue created by itself
    // 如果所有的任务都在"同一个"队列中    // 那么在barrier方法之前添加的任务会先被执行, 只有等barrier方法之前添加的任务执行完毕, 才会执行barrier     // 而且如果是在barrier方法之后添加的任务, 必须等barrier方法执行完毕之后才会开始执行     dispatch_barrier_async(queue, ^{     NSLog(@"barrier --- %@", [NSThread currentThread]); });
    • Case: Tasks 4 and 5 must be performed after 1 and 2
 dispatch_queue_t queue = Dispatch_queue_create ("Com.520it.lnj", dispatch_queue_concurrent);Dispatch_async (Queue, ^{nslog (@ "1---%@", [NSThread CurrentThread]); }); dispatch_async (queue, ^{nslog ( @ "2---%@", [nsthread CurrentThread]);}); Dispatch_barrier_async (queue, ^{nslog (@ "Barrier---%@", [ Span class= "hljs-built_in" >nsthread CurrentThread]); }); dispatch_async (queue, ^{nslog ( @ "4---%@", [nsthread CurrentThread]);}); dispatch_async (queue, ^{nslog ( @ "5---%@", [nsthread CurrentThread]);    
5. Queue Groups
    • Execute sequentially, such as downloading two images from the web and merging the two images into a single piece that is eventually displayed on the view
GCD Group1. Create a queuedispatch_queue_t queue = Dispatch_queue_create ("Com.520it.lnj", dispatch_queue_concurrent);Create a group of dispatch_group_t groups = Dispatch_group_create ();2. Add a download Image task Dispatch_group_async (group, queue, ^{Nsurl *url = [Nsurl URLWithString:@ "Http://stimgcn1.s-msn.com/msnportal/ent/2015/08/04/7a59dbe7-3c18-4fae-bb56-305dab5e6951.jpg"];NSData *data = [NSData Datawithcontentsofurl:url];Self. Image1 = [UIImage Imagewithdata:data];NSLog (@ "Download picture 1%@", [Nsthread CurrentThread]); });3. Add a Download Image task Dispatch_group_async (group, queue, ^{Nsurl *url = [Nsurl URLWithString:@ "Http://y1.ifengimg.com/cmpp/2015/08/05/04/15495f65-5cd2-44cd-a704-bc455d629fe3_size25_w510_h339.jpg"];NSData *data = [NSData Datawithcontentsofurl:url];Self. Image2 = [UIImage Imagewithdata:data];NSLog (@ "Download picture 2%@", [Nsthread CurrentThread]); }); Dispatch_group_notify (group, queue, ^{NSLog (@ "Composite picture%@", [Nsthread CurrentThread]);1. Create picture Context Uigraphicsbeginimagecontext (Cgsizemake (200,200));2. Draw the first picture [Self. Image1 Drawinrect:cgrectmake (0,0,100,200)]; ///3. Draw the second picture [self. Image2 Drawinrect:cgrectmake (0,   200)]; //4. Remove the picture from the context UIImage *res = Uigraphicsgetimagefromcurrentimagecontext (); //5. Close context Uigraphicsendimagecontext (); //6. Go back to the main thread update UI Dispatch_async (Dispatch_get_main_queue (), ^{ NSLog (@ "Update UI%@", [Nsthread CurrentThread]); Self . ImageView. Image = Res;}            ); 
6.6. Inter-thread communication
dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{// 执?耗时的异步操作...dispatch_async(dispatch_get_main_queue(), ^{// 回到主线程,执?UI刷新操作});});

ios--Multi-thread 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.