iOS Development Multithreading Chapter-GCD Introduction

Source: Internet
Author: User
Tags gcd

iOS Development Multithreading Chapter-GCD Introduction

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. Click the +a button to import the frame. (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

There are 2 core concepts in GCD

(1) Task: what action to perform

(2) Queue: for storing tasks

The use of GCD is a 2-step process

(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

Tip: The removal of a task follows the FIFO principle of the queue: first-in, last-out

III. implementation of the mandate

There are 2 functions in the 1.GCD to perform a task

Note: The right parameter (Task) is submitted to the left parameter (queue) for execution.

(1) Perform the task Dispatch_sync (dispatch_queue_t queue, dispatch_block_t block) in a synchronous manner;

Parameter description:

Queue: Queues

Block: Task

(2) Execute the task Dispatch_async asynchronously (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

1. Types of queues

The GCD queue can be divided into 2 major types

(1) Concurrent queues (Concurrent Dispatch queue)

Multiple tasks can be executed concurrently (simultaneously) (automatically opening multiple threads simultaneously) concurrency features are only valid under asynchronous (Dispatch_async) 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. Additional Information

There are 4 terms that are more easily confused: synchronous, asynchronous, concurrent, serial

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. 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); Queue name, queue property, general null

Example:

dispatch_queue_t queue = dispatch_queue_create ("wendingding", NULL); Create

Dispatch_release (queue); Non-Arc needs to release manually created queues

(2) using the primary queue (the queue associated with the mainline threads)

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

Example:

dispatch_queue_t queue = Dispatch_get_main_queue ();

4. Concurrent queues

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); This parameter is temporarily useless and can be used with 0

Example:

This parameter is reserved for later use, temporarily not used, pass a 0. The first parameter is the priority, where the default is selected. Gets a global default priority for concurrent queues.

dispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default, 0); Get global concurrency Queue

Description: Priority for global concurrent queues

#define DISPATCH_QUEUE_PRIORITY_HIGH 2//High

#define DISPATCH_QUEUE_PRIORITY_DEFAULT 0//default (Medium)

#define Dispatch_queue_priority_low (-2)//Low

#define Dispatch_queue_priority_background int16_min//Backstage

5. Execution effect of various queues

Five, code example

(1) Adding a task to the concurrent queue with an asynchronous function

1//2//  YYVIEWCONTROLLER.M 3//  08-GCD Basic use 4//5//  Created by Apple on 14-6-24.6//  Copyright (c) 201 4 years itcase. All rights reserved. 7//8  9 #import "YYViewController.h" @interface Yyviewcontroller () @end14 @implementation Yyviewcontrol Ler16-(void) viewDidLoad18 {     [super viewdidload];20     //1. Get global concurrency queue    dispatch_queue_t queue =  Dispatch_get_global_queue (dispatch_queue_priority_default, 0);     //2. Add tasks to the queue to perform tasks     Async functions: Ability to open new threads     dispatch_async (queue, ^{25         NSLog (@ "Download image 1----%@", [Nsthread CurrentThread])     ;     Dispatch_async (queue, ^{28         NSLog (@ "Download image 2----%@", [Nsthread CurrentThread]);     Dispatch_async (queue, ^{31         NSLog (@ "Download image 2----%@", [Nsthread CurrentThread]);     33//Print main thread     NSLog (@ "Main thread----%@", [Nsthread Mainthread]);     }37 @end

Summary: Open three sub-threads at the same time

(2) Adding tasks to the serial queue with an asynchronous function

 1//2//YYVIEWCONTROLLER.M 3//09-GCD Basic use 2 4//5//Created by Apple on 14-6-24.6//Copyright (c) 2014 it Case. All rights reserved. 7//8 9 #import "YYViewController.h" @interface Yyviewcontroller () @end14 @implementation Yyviewcontroller (void) ViewDidLoad18 {[Super viewdidload];20 21///Print main thread: NSLog (@ "main thread----%@", [Nsthread Mainthrea D]); 23 24//Create serial queue dispatch_queue_t queue= dispatch_queue_create ("wendingding", NULL); 26//The first parameter is the name of a serial queue Called, is the C language of the string 27//The second parameter is a queue of properties, generally speaking the serial queue does not need to assign any properties, so usually null value (NULL) 28 29//2. Add a task to the queue to execute the Dispatch_async (queue, ^{3 1 NSLog (@ "Download picture 1----%@", [Nsthread CurrentThread]); Dispatch_async (queue, ^{34 NSLog (@ "Download Image 2 ----%@ ", [Nsthread CurrentThread]); Dispatch_async (queue, ^{37 NSLog (@" Download picture 2----%@ ", [Nsthread Curre Ntthread]); 38}); 39 40//3. Release resources//Dispatch_release (queue),}43 @end 

Summary: Threads are turned on, but only one thread is opened

(3) Adding a task to the concurrent queue with a synchronous function

1//2//  YYVIEWCONTROLLER.M 3//  10-CGD Basic Use 3 4//5//  Created by Apple on 14-6-24.6//  Copyright (c) 20 14 Itcase. All rights reserved. 7//8  9 #import "YYViewController.h" @interface Yyviewcontroller () @end14 @implementation Yyviewcontrol Ler16/**17  *  Add a task to a concurrent queue with a synchronization function.  */19-(void) VIEWDIDLOAD20 {     [super viewdidload];22]     /print main thread     NSLog (@ "main thread----%@", [Nsthread mainthread]); +/     /create serial queue     dispatch_queue_t  Queue= dispatch_get_global_queue (dispatch_queue_priority_default, 0);     Add a task to the queue to execute     Dispatch_sync (queue, ^{32         NSLog (@ "Download picture 1----%@", [Nsthread CurrentThread]);     Dispatch_sync ( Queue, ^{35         NSLog (@ "Download picture 2----%@", [Nsthread CurrentThread]);     Notoginseng     dispatch_sync (queue, ^{38         NSLog (@ "Download picture 3----%@", [Nsthread CurrentThread]);     }41 @end

Summary: New threads are not opened and concurrent queues lose concurrency

(4) Adding a task to the serial queue with a synchronous function

1//2//  YYVIEWCONTROLLER.M 3//  11-CGD Basic use 4 4//5//  Created by Apple on 14-6-24.6//  Copyright (c) 20 14 Itcase. All rights reserved. 7//8  9 #import "YYViewController.h" @interface Yyviewcontroller () @end14 @implementation Yyviewcontrol Ler16/**19  * Add a task to the serial queue with a synchronous function.  */21-(void) viewDidLoad22 {     [super viewdidload];24      NSLog (@) Add a task to the serial queue with a synchronous function ");/     /print main thread     NSLog (@" main thread----%@ ", [Nsthread mainthread]);/     /create serial queue 29     dispatch_queue_t  queue= dispatch_queue_create ("wendingding", NULL);     Add task to queue execution 32     dispatch_sync (queue, ^{33         NSLog (@ "Download picture 1----%@", [Nsthread CurrentThread]);     Dispatch_ Sync (queue, ^{36         NSLog (@ "Download image 2----%@", [Nsthread CurrentThread]);     dispatch_sync (queue, ^{39         NSLog (@ "Download picture 3----%@", [Nsthread CurrentThread]);     }42 @end

Summary: New threads are not opened

(5) Supplement

Add: The role of the queue name:

When you debug in the future, you can see which queue the task is executing in.

(6) Summary

Description: The synchronization function does not have the ability to open threads, no matter what queue does not open the thread, the asynchronous function has the ability to open threads, open a few threads by the queue (the serial queue will only open a new thread, the concurrent queue will open multiple threads).

Synchronization functions

(1) Concurrent queue: no thread

(2) Serial queue: no thread

Asynchronous functions

(1) Concurrent queue: can open n threads

(2) Serial queue: Open 1 threads

Add:

In all functions, the names of functions, such as create\copy\new\retain, need to be release when the data is not needed. The GCD data type does not need to be release in the ARC environment. The data type of the CF (core Foundation) is still required for release in the ARC environment. Asynchronous functions have the ability to thread, but not necessarily the thread

iOS Development Multithreading Chapter-GCD Introduction

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.