Cat learn iOS (50) A brief introduction to the GCD of multithreaded networks (tasks, queues)

Source: Internet
Author: User
Tags gcd

Cat Share, must boutique

Original articles, welcome reprint. Reprint Please specify: Sanayu's Blog
Address: http://blog.csdn.net/u013357243?viewmode=contents

GCD 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 + 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, LIFO, and backward.

Perform tasks

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

Queue

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 Queue (Serial Dispatch queue)

Let the task execute one after the other (once a task has finished executing, then the next task is performed)

2) Serial Queue (Serial Dispatch queue)

Let the task execute one after the other (once a task has finished executing, then 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_t0// 获得全局并发队列

Description: Priority for global concurrent queues

#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 // 后台

5. Execution effect of various queues

code example GCD Task queue add a task to the concurrent queue with an asynchronous function:
#import "NYViewController.h"  @interface nyviewcontroller ()@end @implementation nyviewcontroller - (void) viewdidload{[SuperViewdidload];//1. Obtaining a global concurrent queue   dispatch_queue_tQueue = Dispatch_get_global_queue (Dispatch_queue_priority_default,0);//2. Add a task to a queue to perform a task    //Async functions: Ability to open new threads    Dispatch_async(Queue, ^{NSLog(@"Download picture 1----%@",[NsthreadCurrentThread]); });Dispatch_async(Queue, ^{NSLog(@"Download picture 2----%@",[NsthreadCurrentThread]); });Dispatch_async(Queue, ^{NSLog(@"Download picture 2----%@",[NsthreadCurrentThread]); });//Print main thread    NSLog(@"Main thread----%@",[NsthreadMainthread]);}@end

Summary: Open three sub-threads at the same time

Add a task to the serial queue with an asynchronous function
- (void) viewdidload{[SuperViewdidload];//Print main thread    NSLog(@"Main thread----%@",[NsthreadMainthread]);//Create serial queue    dispatch_queue_tQueue= Dispatch_queue_create ("Wendingding",NULL);//The first parameter is the name of the serial queue and is a C-language string    ///The second parameter is a property of the queue, in general the serial queue does not need to assign any attributes, so the null value is usually passed (null)    //2. Adding tasks to the queue execution    Dispatch_async(Queue, ^{NSLog(@"Download picture 1----%@",[NsthreadCurrentThread]); });Dispatch_async(Queue, ^{NSLog(@"Download picture 2----%@",[NsthreadCurrentThread]); });Dispatch_async(Queue, ^{NSLog(@"Download picture 2----%@",[NsthreadCurrentThread]); });//3. Releasing Resources//Dispatch_release (queue);}


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

Add a task to a concurrent queue with a synchronization function
/** * Add a task to the concurrent queue with a sync function * /- (void) viewdidload{[SuperViewdidload];//Print main thread    NSLog(@"Main thread----%@",[NsthreadMainthread]);//Create serial queue    dispatch_queue_tQueue= Dispatch_get_global_queue (Dispatch_queue_priority_default,0);//2. Adding tasks to the queue execution    Dispatch_sync(Queue, ^{NSLog(@"Download picture 1----%@",[NsthreadCurrentThread]); });Dispatch_sync(Queue, ^{NSLog(@"Download picture 2----%@",[NsthreadCurrentThread]); });Dispatch_sync(Queue, ^{NSLog(@"Download picture 3----%@",[NsthreadCurrentThread]); });}

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

Add a task to the serial queue with a sync function
/** * Add a task to the serial queue with a sync function * /- (void) viewdidload{[SuperViewdidload];NSLog(@"Add a task to a serial queue with a synchronous function");//Print main thread    NSLog(@"Main thread----%@",[NsthreadMainthread]);//Create serial queue    dispatch_queue_tQueue= Dispatch_queue_create ("Wendingding",NULL);//2. Adding tasks to the queue execution    Dispatch_sync(Queue, ^{NSLog(@"Download picture 1----%@",[NsthreadCurrentThread]); });Dispatch_sync(Queue, ^{NSLog(@"Download picture 2----%@",[NsthreadCurrentThread]); });Dispatch_sync(Queue, ^{NSLog(@"Download picture 3----%@",[NsthreadCurrentThread]); });}

Summary: New threads are not opened

Add

Add: The role of the queue name:

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

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

G? D need to master (very important) 1. Queues and Tasks

1> tasks: What needs to be done
* Use block to encapsulate tasks

2> Queues: Storing tasks
* Global Concurrent queue: Allows tasks to execute concurrently

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    • Create a serial queue yourself: Let the task execute one after the other
dispatch_queue_t queue = dispatch_queue_create("cn.heima.queue"NULL);
    • Master queue: Let the task execute on the main thread
dispatch_queue_t queue = dispatch_get_main_queue();
2. Functions that perform tasks

1> synchronous execution: Does not have the ability to open new threads

dispatch_sync...

2> Asynchronous execution: Ability to open new threads

dispatch_async...
3. Common combinations (master)

1> dispatch_async + global concurrency queue
2> Dispatch_async + self-created serial queue

4. Communication between threads (mastering)
0), ^{   // 执行耗时的异步操作...   dispatch_async(dispatch_get_main_queue(), ^{       // 回到主线程,执行UI刷新操作   });});
All 5.GCD APIs are automatically imported into this library at Libdispatch.dylib,xcode.
    • Primary header file: #import
6. Deferred Execution (master)

1> perform ....
After 3 seconds automatically returns to the current thread called Self's Download: method, and passes the parameter: @ "Http://555.jpg"
[Self performselector: @selector (Download:) withobject:@ "http://555.jpg" afterdelay:3];

2> Dispatch_after ...
Which queue the task is placed in to execute
dispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default, 0);
Double delay = 3; How many seconds are delayed
Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (Delay * nsec_per_sec)), queue, ^{
Tasks that need to be performed after 3 seconds
});

7. Disposable code (Master)

Static dispatch_once_t Oncetoken;
Dispatch_once (&oncetoken, ^{
The code inside is always executed 1 times during the program's operation.
});

Cat learn iOS (50) A brief introduction to the GCD of multithreaded networks (tasks, queues)

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.