Multithreaded usage with GCD in iOS

Source: Internet
Author: User
Tags gcd

GCD Introduction
GCD full name Grand Central Dispatch, can be translated as "awesome Hub scheduler".
Pure C language, provides a lot of powerful functions.
GCD Advantages:
GCD is the solution that Apple has proposed 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 (creating threads, scheduling tasks, destroying threads).
Programmers simply need to tell gcd what tasks they want to perform, without having to write any thread-management code.

Tasks and Queues

There are 2 core concepts in GCD
Task: what action to take.
Queue: Used to store tasks.

The use of GCD is a 2-step process
customizing tasks
Identify the things you want to do

Add a task to a queue
GCD automatically takes the tasks in the queue and executes them in the corresponding thread.
The removal of a task follows the FIFO principle in the queue: first-in, LIFO, and backward-out.

Perform Tasks

There are 2 functions for performing tasks in GCD
Perform tasks in a synchronous manner.
Dispatch_sync (dispatch_queue_t queue, dispatch_block_t block);
Queue: Queues
Block: Task

Perform a task in an asynchronous manner
Dispatch_async (dispatch_queue_t queue, dispatch_block_t block);
The difference between synchronous and asynchronous:
Synchronous: Executes in the current thread.
Async: Executes in another thread.

Types of Queues

The GCD queue can be divided into 2 major categories
Concurrent queues (Concurrent Dispatch queue)
Multiple tasks can be executed concurrently (concurrently) (automatically opening multiple threads concurrently executing tasks).
Concurrency functionality is only valid under asynchronous (Dispatch_async) functions.

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)

easy to confuse terminology

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 and does not have the ability to open a new thread.
Async: Performs a task in a new thread, with the ability to open a new thread.
Concurrency and serial determination of how tasks are performed
Concurrency: Multiple tasks concurrently (concurrently) executed

concurrent (parallel) Queues

The GCD default already provides a global concurrency queue for the entire app to use, and does not need to be created manually.
Use 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);
dispatch_queue_t queue = Dispatch_get_global_queue (dispatch_queue_priority_default,0);//Get Global concurrent queue
Priority of 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

There are 2 ways to get serial in GCD
To create a serial queue using the Dispatch_queue_create function
dispatch_queue_t
Dispatch_queue_create (const char *label,//queue name
dispatch_queue_attr_t attr);//queue properties, generally null
dispatch_queue_t queue = dispatch_queue_create ("Cn.itcast.queue", NULL);//Create
Dispatch_release (queue);//non-ARC requires manual creation of queues

Use the primary queue (the queue associated with the mainline threads)
The primary queue is a special serial queue that comes with the GCD.
Tasks that are placed in the main queue are placed in the main thread to be executed.
Use Dispatch_get_main_queue () to get the home row
dispatch_queue_t queue = Dispatch_get_main_queue ();

Execution effects for various queues

inter-thread communication

Returning from a child thread to the main thread
Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{
Perform time-consuming asynchronous operations

Dispatch_async (Dispatch_get_main_queue (), ^{
Go back to the main thread and perform a UI refresh operation

});
});

deferred execution
There are 2 ways that iOS typically delays execution
Methods for calling NSObject
[Self performselector: @selector (Run) Withobject:nil afterdelay:2.0];
Using the GCD function
Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (2.0 *nsec_per_sec)), Dispatch_get_main_queue (), ^{
Execute the code here asynchronously after 2 seconds
});

Disposable Code
Use the Dispatch_once function to ensure that a piece of code is executed only 1 times during program operation
Static dispatch_once_t Oncetoken;
Dispatch_once (&oncetoken, ^{
Execute code only 1 times (this is thread-safe by default)
});

Queue Group
There is such a demand
First: Perform 2 time-consuming operations asynchronously, respectively
Second: Wait for 2 asynchronous operations to complete, then return to the main thread to perform the operation

If you want to implement these requirements quickly and efficiently, consider using queue groups
dispatch_group_t group = Dispatch_group_create ();

Dispatch_group_async (Group, Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{
Perform 1 time-consuming asynchronous operations
});

Dispatch_group_async (Group, Dispatch_get_global_queue (Dispatch_queue_priority_default, 0), ^{
Perform 1 time-consuming asynchronous operations
});
Dispatch_group_notify (Group, Dispatch_get_main_queue (), ^{
When the previous asynchronous operation is complete, return to the main thread ...
});

Multithreaded usage with GCD in iOS

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.