iOS Multithreading implementation 3-GCD

Source: Internet
Author: User

Knock down GCD Three letters, Sogou first show is actually "roll the sheet" ^_^

First, Introduction

GCD, the English full name is the Grand Central Dispatch (centralized dispatcher of powerful function), a set of multithreaded development mechanism written in C language, so it appears as a function, and most functions begin with Dispatch. Although it is the C language, but relative to Apple other multi-threaded implementation way, the abstraction level is higher, the use is also more convenient.

It is an Apple solution for multi-core parallel computing, which automatically uses multicore for concurrent processing and operations, and threads are automatically managed (scheduled, run) by the system, and are easy to use without the programmer's involvement.

Ii. Tasks and queues

GCD has two cores: tasks and queues.

Task: The action or method function to be performed, queue: A collection of tasks, and all we have to do is add the task to the queue and execute it, and GCD automatically takes the task in the queue out of the first-in, out-of-the-way and hands it on to the corresponding thread. Note that the task is taken out of the first-in, in-out way, which is also the characteristics of the queue, but after the execution order is not necessarily, the following will be discussed in detail.

1 Quests

Can be simply considered an operation, a function, a method and so on, in the actual development is mostly in the form of block, the use of more flexible. For block use see: http://www.cnblogs.com/mddblog/p/4754190.html

  2 queues

There are two kinds of queues: Serial queue and parallel queue. Serial queue: Synchronous execution, executed on the current thread, parallel queue: can be executed asynchronously by multiple threads, but the removal of a task is FIFO.

Queue creation, which creates a serial or parallel queue based on the second parameter of the function.

// parameter 1 queue name // parameter 2 queue type Dispatch_queue_serial/null serial queue, Dispatch_queue_concurrent stands for parallel queue // The following code creates a serial queue and is the most dispatch_queue_t Serialq = dispatch_queue_create (" queue name ") used in the actual development  , NULL);

In addition, the system provides two types of queues: Global Queue and Home row.

The global queue belongs to a parallel queue, except that it has been created by the system without a name and is globally visible (available). Get Global queue:

/**/0);

The primary queue is a serial queue and is also created by the system, except that it runs on the main thread (the UI thread). Get the Home column:

// get home row Serialq = Dispatch_get_main_queue ();

3 Mode of execution-2

Synchronous execution and asynchronous execution.

Synchronous execution: The thread is not opened and executed on the current thread.

Asynchronous execution: An idle thread in the GCD managed thread pool will pull the task execution from the queue and the thread will be opened.

The following are functions that implement synchronous and asynchronous functions: adding a task to a queue and executing it.

/**/void  dispatch_sync (dispatch_queue_t queue, dispatch_block_t block); // Asynchronous Execution void Dispatch_async (dispatch_queue_t queue, dispatch_block_t block);

Three, several types

It is obvious that there are two kinds of execution, two kinds of queues. Then there are 4 cases: Serial queue synchronous execution, serial queue asynchronous execution, parallel queue synchronous execution, parallel queue asynchronous execution. Which one will open the new thread? Open a few? Is it concurrent? Memory is more around, but as long as the grasp of the basic can be, in order to facilitate understanding, now analyzed as follows:

1) Serial queue, synchronous execution-----Serial queue means sequential execution, synchronous execution means no threads being opened (executed on current thread)

2) Serial queue, asynchronous execution-----Serial queue means the task order execution, asynchronous execution instructions to the thread, (if the number of threads, can not guarantee serial queue order execution, so only one thread)

3) Parallel queues, asynchronous execution-----Parallel queues means that execution order is indeterminate, asynchronous execution means that threads are turned on, and parallel queues are allowed to execute in order, so that the system will open multiple threads for performance improvement in order to queue up tasks (the queue is still out of order, except that the threads are unordered).

4) Parallel queue, synchronous execution-----Synchronous execution means no thread, it must be sequential execution

5) Main thread in the Host column, Synchronous execution-----Program execution does not come out (deadlock); reason: The primary queue, if the main thread is executing code, does not dispatch the task; synchronous execution: Executes the first task until the end. The two wait for each other to cause a deadlock.

// execute the following code on the main thread, deadlock Dispatch_sync (Dispatch_get_main_queue (), ^{    //  code to execute });

Iv. examples of common use

1 Inter-thread communication

For example, in order to improve the user experience, we generally download images or other network resources on other threads (not the main thread), we will update the UI after the download is complete, and the UI update must be executed on the main thread, so we often use:

// synchronous execution, which will block the code in the following block executes Dispatch_sync (Dispatch_get_main_queue (), ^{    ///  main thread, UI update }); // asynchronously executes Dispatch_async (Dispatch_get_main_queue (), ^{    ///  main thread, UI update });

2 other commonly used

Global queues, Implementing Concurrency:

Dispatch_async (Dispatch_get_global_queue (00), ^{    //  code to execute });

Five, Dispatch group scheduling groups

With scheduling groups, it is easy to do something after some tasks have been completed. such as producer consumers with sequential requirements, and so on.

Example 1 Task 1 completes after you perform task 2.

- (void) Touchesbegan: (Nsset *) touches withevent: (Uievent *)Event{[self grouptest];}- (void) Grouptest {//Creating a groupdispatch_group_t Group =dispatch_group_create (); NSLog (@"Start Execution"); Dispatch_async (Dispatch_get_global_queue (0,0), ^{dispatch_group_async (group, Dispatch_get_global_queue (0,0), ^{            //Task 1//wait 1s for some time to execute[Nsthread Sleepfortimeinterval:1]; NSLog (@"Task1 running in%@", [Nsthread CurrentThread]);        }); Dispatch_group_notify (Group, Dispatch_get_global_queue (0,0), ^{            //Task 2NSLog (@"Task2 running in%@", [Nsthread CurrentThread]);    }); });}

After tapping the screen, print the following, you can see that task 1, while waiting for 1s, task 2 is not executed, only task 1 execution completed before the task 2.

 -- ,- -  -: -:05.317gcdtest[1468:229374] Start Execution -- ,- -  -: -:06.323gcdtest[1468:229457] Task1 Runninginch<nsthread:0x7f8962f16900>{number =2, name = (NULL)} -- ,- -  -: -:06.323gcdtest[1468:229456] Task2 Runninginch<nsthread:0x7f8962c92750>{number =3, name = (NULL)}

Example 2, in fact, example 1 is not commonly used, the real use is to monitor the completion of multiple tasks, back to the main thread to update the UI, or do other things.

- (void) Touchesbegan: (Nsset *) touches withevent: (Uievent *)Event{[self grouptest];}- (void) Grouptest {//Creating a groupdispatch_group_t Group =dispatch_group_create (); NSLog (@"Start Execution"); Dispatch_async (Dispatch_get_global_queue (0,0), ^{dispatch_group_async (group, Dispatch_get_global_queue (0,0), ^{            //Related Tasks 1NSLog (@"Task1 running in%@", [Nsthread CurrentThread]);        }); Dispatch_group_async (Group, Dispatch_get_global_queue (0,0), ^{            //Related Tasks 2NSLog (@"Task2 running in%@", [Nsthread CurrentThread]);        }); Dispatch_group_async (Group, Dispatch_get_global_queue (0,0), ^{            //Related Tasks 3NSLog (@"Task3 running in%@", [Nsthread CurrentThread]);        }); Dispatch_group_async (Group, Dispatch_get_global_queue (0,0), ^{            //Related Tasks 4//wait 1 seconds[Nsthread Sleepfortimeinterval:1]; NSLog (@"Task4 running in%@", [Nsthread CurrentThread]);        }); Dispatch_group_notify (Group, Dispatch_get_main_queue (),^{            //back to main thread executionNSLog (@"Maintask running in%@", [Nsthread CurrentThread]);    }); });}

After tapping the screen, print as follows, and you can see that the maintask waits for them to execute, regardless of the other tasks and then executes.

 -- ,- -  -: -:14.312gcdtest[1554:236273] Start Execution -- ,- -  -: -:14.312gcdtest[1554:236352] Task3 Runninginch<nsthread:0x7fa8f1f0c9c0>{number =4, name = (NULL)} -- ,- -  -: -:14.312gcdtest[1554:236354] Task1 Runninginch<nsthread:0x7fa8f1d10750>{number =2, name = (NULL)} -- ,- -  -: -:14.312gcdtest[1554:236351] Task2 Runninginch<nsthread:0x7fa8f1c291a0>{number =3, name = (NULL)} -- ,- -  -: -:15.313gcdtest[1554:236353] Task4 Runninginch<nsthread:0x7fa8f1d0e7f0>{number =5, name = (NULL)} -- ,- -  -: -:15.313gcdtest[1554:236273] Maintask Runninginch<nsthread:0x7fa8f1c13df0>{number =1, name = main}

iOS Multithreading implementation 3-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.