IOS-summarized under Swift using GCD multithreading (ii) GCD and Dispatchqueue

Source: Internet
Author: User
Tags gcd

1. Preface

There are two techniques for processing multi-core concurrency in iOS: ' Grand Central Dispatch ' (hereinafter referred to as ' GCD ') and ' nsoperationqueue ' frameworks. iOS developed by the old drivers in the program development process to handle multiple tasks at the same time, will be used to both frameworks, and GCD relies on its concise syntax and the use of block has been very popular. iOS Development You must understand the principle that "any operation for UI refresh and user interaction should be done on the main thread, and any time-consuming or CPU-intensive task must be operated on an asynchronous thread ." The old driver said remember it's good--here's a simple explanation:

First of all, let's explain the first sentence: " any action for UI refresh and user interaction is to be placed on the main thread to operate ", To understand this sentence only understand the following points: 1. The main thread is threaded--putting all UI refreshes and user interaction in the main thread operation avoids a lot of surprises and ensures that when the data returned from the server is fetched, the UI interface can refresh the data in a timely and safe manner, giving the user a good experience. Only the main thread in 2.ios can immediately refresh the UI interface, and if it is placed on an asynchronous thread, it will cause thread blocking and latency issues. ---2nd " any task that is time consuming or CPU intensive must be operated on an asynchronous thread "--if you understand the first half of the sentence well, then the meaning of this sentence is well understood, put the time consuming or CPU consuming operation on the asynchronous thread, In order to prevent the blocking delay of the thread, prevent the UI refresh on the main thread and a series of actions of the user to stutter, deadlock, delay and so on.

2. Text

Anyway, we continue to look down, if you are familiar with iOS gcd and dispatchqueue use very skilled, then swift3.0 syntax and use should be pro, if you do not specifically understand GCD is what ghost? It's okay, let's get you some dry foods in the mountains first:

1. ' Dispatch queue ': A bunch of code that executes synchronously (or asynchronously) on the main thread (or background thread), once created, the operating system begins to take over management and allocates a time slice on the CPU to execute the code in the queue. Developers cannot participate in the management of ' queue '. Queue using ' FIFO mode ' (first-out), means that the first to join will be completed first, this and the supermarket queue to pay, before the team always the first to pay out, the truth is the same.

2. ' Work item ': A block of code that can be added when the queue is created, or can be created individually for reuse, you can use it as a block of code that will run on ' queue '. ' Work Items ' also follows the ' FIFO mode ', which can also be performed synchronously (or asynchronously), and if you choose to synchronize, the running program will continue after the code block is completed, relative, if you choose to asynchronous, the running program will immediately return when the code block is triggered.

3. ' Serial ' (serial) vs ' concurrent ' (parallel): ' Serial ' will perform one task before it starts next, ' concurrent ' triggers the next one immediately, regardless of whether it is completed or not.

Next goes to the topic: Swift3.0 in GCD and dispatchqueue use. 1. ' Serial ' (serial) vs ' concurrent ' (parallel) 1.1 Create a Dispatchqueue method:
Is that so simple??

1.2 Next we create a serial queue and compare the code executed in the main thread to see the difference between serial and main thread?
??

Then we execute this method in Viewdidload, and look at the results of the console printing:


??

From the results we can see that two methods are executed sequentially, which means that the serial queue and the main thread are serially output. In other words: The main thread is also a serial queue.

What about asynchronous (parallel) queue execution?


Asynchronous

Look at the output:


Asynchronous results

This time we were pleasantly surprised to find that the functions of the main thread and the function of the asynchronous queue are alternately executed, that is, the output of the synchronization, because the asynchronous queue does not block the current thread but instead opens another thread to perform the current task, and the tasks on the main thread are not blocked, so the two are output synchronously.

We can at least understand two things through the comparison above:

1. Use the async main thread and the background thread to perform tasks in parallel

2. Use sync to perform only serial tasks, the current thread is stuck until the serial task finishes

2.GCD Service level--qos queue

To figure out the relationship between ' serial ' (serial) and ' concurrent ' (parallel), we continue to look at the QoS queue for GCD.

GCD Service level (GCD QoS): Attributes that determine task importance and priority

QoS is a specific scenario-based enumeration type that, when initially queued, provides the appropriate QoS parameters to obtain the appropriate permissions, and if no QoS is specified, the initial method uses the default QoS values provided by the queue

QoS level (QoS classes), from front to back, priority from high to Low:

Userinteractive

userinitiated

Default

Utility

Background

Unspecified

From the above introduction we guess it must be--the higher the rank of the queue is executed first, the queue in the same level of the serial queue is definitely one execution, the asynchronous queue is definitely sub-thread parallel execution--we will verify the following:

2.1 First create a QoS queue:
QoS Queuing

QoS: An enumeration type that needs to pass a Dispatchqos

2.2 Same queue same-level serial output comparison
Qosconcurrentqueues

Look at the output:


Qosconcurrentqueues-log

Looking closely we will find that the results are not parallel to the asynchronous queue in the same hierarchy as we suspect, what is going on? Because QoS queues are executed serially by default, even if the methods in the QoS queue are asynchronous, they are sequentially executed serially. So what can be done in parallel? This will use another attribute of the QoS queue: Attributes:.concurrent

Specific wording:


Parallel to the same level

Look at the specific function and the result of the operation:


Same-level parallel-log1


Same-level parallel-log2

Through the output we found that the results are parallel output, but careful you are not found in the results of the silk, the two attached to the results of the same function is running multiple display of different results, why is it different? Is there a problem with the program, how can a function have two results? is not immediately a face Meng force, 10,000 grass mud horse in the heart Pentium???????????????????????????????? -----donor propitiate, wait for the mountain Eva slowly to you analysis:

First of all we need to understand that the system so-called parallel execution, not all of us imagine that the kind is fixed like log1 in the same very regular output, the internal is the resource of the tilt or the order of uncertainty, continue to look at the following example you will be thoroughly understood.

We look at the results with a new QoS queue of different levels:


QoS at different levels

Output Result:


Different grades Qos-log3

Looking at the results, we will find that the queue that we previously guessed is not as high as the first one, but a high-level and low-level crossover to output, carefully thinking that this is the perfect interpretation of the problem above, the system will make the higher priority ' queue1 ' than ' queue2 ' faster execution, although the ' Queue1 ' run ' queue2 ' get a chance to run, the system is still to tilt the resources to be labeled more important ' queue1 ', and so on ' queue1 ' tasks are all executed, the system began to serve the ' queue2 ' wholeheartedly. ---See here you should understand.

You can think of a question, in which tier is the main queue main Line queued? Let's take a look at the following example:


Main queue Comparison

Results:


Results

We can clearly conclude that the ' main queue ' has a high privilege by default.

Next we are looking at another attribute of the QoS queue attributes, Initiallyinactive (inactive), we can create an inactive queue of QoS, which is characterized by the need to invoke the Dispatchqueue class ' activate () ' Let the task execute. Look at the specific code:


Initiallyinactive queue

The focus is on the following, called in Viewdidload:


Initiallyinactive Queue Call

Look at the output:


Initiallyinactive Queue-log

We find that the queue is serial output, so how to create a parallel initiallyinactive queue? View API We'll find that the attributes of the QoS queue is receiving an array, so you must know what to do with the smart one.


Initiallyinactive Parallel queue 3. Deferred execution

When a task in one of your applications delays execution, GCD allows you to execute a method to run the purpose of your specified task after a specific time. Directly on the code:


Lazy Loading

Here is an explanation: the. Now () method is to get the current time.

4.DispatchWorkItem

Dispatchworkitem is a block of code that can be divided into any queue that contains code that can be executed in the background or the main thread, simply: It is used to replace the block of code we wrote earlier to invoke. It's also easy to use, see the code:


DISPATCHWORKITEM5. Main thread Update UI

Finally, let's share a first example of the main thread refresh UI, look at the code:


Main thread Update UI

Remember to call Setingimage () This method in Viewdidload when you use it.

Here I would like to introduce you to the lazy loading in swift and OC in the similarities and differences, the individual summed up below you can see:


Lazy Loading

The mountain _ in _ Eva
Links: Http://www.jianshu.com/p/737233208d40
Source: Pinterest
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

IOS-summarized under Swift using GCD multithreading (ii) GCD and Dispatchqueue

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.