An in-depth gcd of iOS multithreaded development

Source: Internet
Author: User
Tags gcd

An in-depth gcd of iOS multithreaded developmentFirst, preface

in previous series of blogs, the management of iOS threads was summarized, covering the basics of GCD: http://my.oschina.net/u/2340880/blog/417746. There will be GCD thread management capabilities, queue group capabilities, through the signal and Message control program flow capabilities are introduced, here, we continue to delve into GCD function, through the GCD to deal with some logic more complex code functions.

second, delay the task of appending

when we are dealing with the delay task in the program, we generally use two methods, one is the timer to execute the delay, the other is through the following function:

-(void) Performselector: (SEL) Aselector withobject: (ID) anargument afterdelay: (nstimeinterval) delay;

However, if we need to delay the operation in multi-threading, the above two methods will be very cumbersome and increase the complexity of the code. GCD provides us with a way to:

void Dispatch_after (dispatch_time_t when, dispatch_queue_t queue, dispatch_block_t block);

This method has three parameters, the first parameter is the delay time, the second parameter is the queue to join the task, and the third block is the task to be performed. Examples are as follows:

Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (3 * nsec_per_sec)), Dispatch_get_main_queue (), ^{NSLog (@    "1233"); });

Here, the time object is created by Dispatch_time, and the method of printing information is added to the main thread queue after 3S. It is important to note that this is simply a queue for task delay, not execution, and if it is joined to the synchronization queue, it will go into a wait state.


Third, the thread safety of data access

In multi-threaded programming, there may always be a class of problems, data competition and thread security. These problems can be very large if we manually control the difficulty through the program. GCD also for us to solve this problem simply.

First, if you're just reading data and not making any changes to the data, we don't have to deal with security issues, we can have multiple tasks read at the same time, but if you want to write to the data, We have to have only one task to write, there is a way to help us solve the problem perfectly, the code is as follows:

GCD

Create a queue dispatch_queue_t queue = dispatch_queue_create ("Onequeue",  dispatch_queue_ CONCURRENT)     //Several tasks simultaneous read operation     dispatch_async (queue, ^{         for  (int i=0; i<5; i++)  {             nslog (@ "read1:%d", i);         }    });     dispatch_async (queue, ^{         for  (int i=0; i<5; i++)  {             nslog (@ "read2:%d", i);         }    });     //here write operations      /*     The following function does not execute when it joins the queue, it waits for the asynchronous execution that has already begun to complete before it executes, and when it does, it blocks other tasks      After execution completes, other tasks re-enter asynchronous execution &NBSP;&NBSP;&NBSP;&NBSP;*/&NBsp;       dispatch_barrier_async (queue, ^{         for  (int i=0; i<5; i++)  {             nslog (@ "write:%d", i);         }    });     //continue with asynchronous read operations     dispatch_async ( queue, ^{        for  (int i=0; i<5; i++)  {            nslog (@ "read3:%d", i);         }    });     dispatch_async ( queue, ^{        for  (int i=0; i<5; i++)  {            nslog (@ "read4:%d", i);         }    });     dispatch_async (queue, ^{         for  (int i=0; i<5; i++)  {             nslog (@ "read5:%d", i);         }    });

Print the following information:


As you can see, the read operation is asynchronous, and the write operation is to wait for the block task queue to proceed independently, and after the end the queue resumes executing the read asynchronously, which is exactly the effect we need.


Iv. Single example of GCD pattern

Typically, our single meeting looks like this:

+ (instancetype) shared{static Auto * OBJ;    if (obj==nil) {obj = [[Auto alloc]init]; } return obj;

This way of reading static variables is not a problem in most cases, but it does not guarantee the program hundred percent security, because in multi-threaded operation, it is possible to initialize multiple objects, in GCD, we can use the following methods:

+ (instancetype) shared{static Auto * OBJ;    The dispatch_once_t object can be guaranteed to perform only one static dispatch_once_t once;    Dispatch_once (&once, ^{obj = [[Auto alloc]init];     });    return obj; }


An in-depth gcd of iOS multithreaded development

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.