IOS 17th: Grand Central Dispatch (GCD) programming Basics

Source: Internet
Author: User

People with programming experience will basically be exposed to multithreading.

In Java and Android development, a large number of background operations and asynchronous message queues are basically implemented using multithreading.

Similarly, IOS Mobile development and Android are basically similar models.

However, many times, in application development, we will find that we do not have to code ourselves to handle some concurrent events, to open up new sub-threads, and so on.

(Although the system usually calls the SDK to initiate a network request, a new thread will be sent to you by default ).

The entire program seems to be basically executed in the main thread.

This is indeed the case, because we are basically operating on the control layout, adding control data, and updating UI objects in the main thread.

Even if we see that we have enabled a new sub-thread to obtain and process data, we still need to notify the UI main thread to refresh it.

Of course, IOS itself is the same as most languages, with nsthread thread classes (we all know that we use this class in Java ).

These systems are relatively underlying API classes that can be used to write their own concurrent threads and operation queues.

After learning Android, we all know the concept of handler and logoff. logoff is a message loop queue of the main thread. Handler generally understands that it is used for data interaction between the subthread and the main UI thread.

After reading the GCD features of iOS, I found that they are quite similar.

1. Next let's take a look at how to use the asynchronous programming method of GCD.

Dispatch_async (dispatch_get_global_queue (0, 0), ^ {// code block for processing time-consuming operations... // notify the main thread to refresh dispatch_async (dispatch_get_main_queue (), ^ {// callback or notify the main thread to refresh ,});});

Dispatch_async enables an asynchronous operation. The first parameter is to specify a GCD queue, and the second parameter is to assign a program block to the queue for transaction processing.

Dispatch_get_global_queue (0, 0) indicates that a global queue is used.

Generally, the system itself has three queues.

Global_queue, current_queue, and main_queue.

To obtain a global queue, two parameters are accepted. The first parameter is the priority of the transaction processing block queue that I assign. The default value is "2". The default value is "2". The default value is "-2 ".

#defineDISPATCH_QUEUE_PRIORITY_HIGH  2#defineDISPATCH_QUEUE_PRIORITY_DEFAULT  0#defineDISPATCH_QUEUE_PRIORITY_LOW (-2)

After processing a transaction, you need to return the result to or refresh the UI main thread. Similarly, as above, the main thread is crawled and the block operation is performed.

// Oh, my god. I accidentally clicked on the home room. I will step back and find that I didn't save it ~~~ No concurrent content is written !!!

Ii. Concept of concurrency in GCD

In fact, we have always mentioned several concepts in programming, such as synchronization, Asynchronization, concurrency, and lock.

Sometimes I think it's hard to tell.

The image loading mentioned above shows my understanding of these three concepts.

1 synchronization:

   for (int i = 0 ; i < 10; i++) {               UIImage *img = [self getImgeWith:[urlArr objectForIndex:i]];          [myImgV[i] setImage:img];            }

Assume that I want to load 10 images. Now I have the resource addresses of these images and save them in an array.

Let's take the first image for example:

The concept of synchronous execution is that after I get the first image,

After the first sentence of the For Loop is executed and the IMG is returned, I can execute the second sentence to refresh the UI interface.

If it takes 10 seconds to return the first sentence, the response of my program seems to have been stuck here, and I cannot perform other operations. Wait until it returns !!

Therefore, a well-understood concept of synchronization is that one step goes to the dark.

2. asynchronous

For (INT I = 0; I <10; I ++) {dispatch_async (dispatch_get_global_queue (0, 0), ^ {// code block for processing time-consuming operations... uiimage * IMG = [self getimgewith: [urlarr objectforindex: I]; // notify the main thread to refresh dispatch_async (dispatch_get_main_queue (), ^ {// callback or notify the main thread to refresh, [myimgv [I] setimage: img] ;});

After reading this code, we will say that the asynchronous operation still takes 10 seconds. In general, it still takes about 10 seconds to load an image,

It seems that Asynchronization is useless. However, do not ignore either of them or the core of the black silk. At this time, we put the image acquisition operation in a thread queue,

At this moment, although we still need 10 seconds to see the image loading, during this 10 seconds, our main UI thread can operate, for example, if there is a button on the interface, you can press

Instead of synchronizing the above, I can only wait and do nothing during the 10th period.

The core concept of Asynchronization is a new thread and a message callback notification.

3. Parallel

The above code is used as an example. As I mentioned above, we only watch the loading of one image. Now, we can go back to the thinking of seeing the code at first glance,

A For loop. In fact, after the code above, I created 10 asynchronous threads.

Well, here we should understand these three concepts.

Synchronization, in fact, the previous example has some limitations, that is, this example itself indicates that no synchronization is required, and it makes everyone feel like

Synchronization is a taboo in programming. In fact, it is not the case. Many times. We really need to implement some synchronization restrictions (such as the synchronization lock proposed in the thread? Is it useful to listen?

Although synchronization may not be used as we thought, at least this concept is also useful)

I will give a simple example of how to use the benefits of synchronization by loading the image just now.

Of course, I just simulate a synchronization scenario.

Assume that the current image is loaded like this. The image itself is a default image before loading. It says, click "I load" and then the network loading method will be called, then the image is loading,

Then, when we double-click an image (of course, after loading it in theory), we can read the image network image to enlarge it. Well, here we should be able to think about the situation to express.

The entire process is to click the image-> load-> double-click to view. If you click-> load (to return the author and information of the image)-> double-click the image (to display the large image through the large image link returned in the previous request)->

Returns the full load (returns the link to the larger image ). Now we can't see the big image. Because our operation is before the return, that is,

Most of the time, when we need to use the data of the previous operation for the next operation, we will do the synchronization programming for him, such as adding a lock.

This is what we will be wondering: The next execution needs to use the previous execution. Isn't the second sentence of the for loop in the first example used?

They have to synchronize. If you think so, it's a coincidence that we have come up with something ~

However, note that the previous asynchronous operation aims to solve the problem of clicking other buttons instead of updating the UI. In our opinion, the download and update UI operations must be synchronized.

This is correct, but it causes some listening events of the system to listen to the click Processing request, and the image loading here is actually regarded as an event execution,

This abstract unit of events is actually a kind of extensiveness that can be defined by humans.

That is to say, a data acquisition and image filling are actually an image acquisition and loading event. An event can be said to contain two units, loading and filling.

The entire event does not matter if we click other buttons, which means no synchronization is required.

It makes sense, but if we want to click this image, we will return to the assumption that we can double-click it.

In this case, why can we click double-click to load the image? In this case, we assume that the image retrieval is asynchronous, but we need to synchronize the next step.

Therefore, human synchronization locks are performed.

Okay, too much. At that time, we understood at least two points.

Asynchronous mode may be used to block the main thread caused by time-consuming operations,

Synchronization aims to solve unnecessary errors and troubles. Perhaps here, we will think of the so-called thread security in our minds.

In fact, synchronization and synchronization locks should take into account such unnecessary and insecure factors.

Finally, the asynchronous and concurrent relationships are briefly described.

As mentioned above, Asynchronization only provides the concept of multi-thread processing,

Concurrency is more like a large-scale asynchronous implementation.

For example, I proposed asynchronously that I could use my younger brother to collect the protection fee, finish the charge, and give it to myself, while I did other things during the period.

Concurrency suddenly comes to mind that Asynchronization makes sense. I have four places to accept and one younger brother to accept it. Although I can still do other things in my spare time,

However, the younger brother ran four places and it took me the same time to get the money, but I didn't have to work that hard and could do other things.

Therefore, the concurrency thinks four younger siblings should be dispatched, because the protection fee for each site is irrelevant. (I just saw a New York gangster ~).

Therefore, Asynchronization solves thread congestion, while concurrency improves the processing time efficiency of event that meets the characteristics on the basis of Asynchronization.

Of course, if the 10 images are unrelated to each other, but the last event needs to be processed to calculate the total capacity of the 10 images.

You can use dispatch_group_async.

For more information, see the document.

In general, I have read iosgcd. First, I am familiar with the block programming features and how to use the GCD features provided by IOS.

To complete multi-threaded programming.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.