GCD in iOS

Source: Internet
Author: User
Tags gcd

Excerpt from: http://www.cocoachina.com/swift/20150129/11057.html

Libdispatch is a library provided by Apple for concurrent programming on iOS and OS X, and GCD is its market name. GCD has the following advantages: –GCD can put computationally complex tasks in the background to improve the response performance of the app –GCD provides a simpler concurrency model than locks and threads, helping developers avoid concurrency bugs.

To understand GCD, you need to understand some of the concepts of threading and concurrency. These concepts may be vague and subtle, so let's review them briefly.

Serial vs concurrency

These two words are used to describe the order in which tasks are executed. Serially always executes a single task at the same point in time, while concurrently performing multiple tasks concurrently.

Task

In this tutorial, you can think of a task as a closure (closure). In fact, you can use GCD with function pointers, but this is rarely used in general. It's easier to close the bag!

Don't remember the closures in Swift? Closures are self-contained and can hold code blocks that are passed and called. When called, their usage is much like a function, which can have parameters and return values. In addition, closures can "capture" external variables, which means that they can see and remember the scope variables that are defined when they are themselves.

Closures in Swift are similar to blocks in OC, even if they are almost interchangeable. The only limitation is that the features that are unique to swift, such as tuples (tuple), cannot be used in OC. However, blocks in OC can be safely replaced with closures in Swift.

Synchronous vs Asynchronous

These two words describe when a function returns control to the caller, and the completion of the task on return.

Synchronization functions are not returned until the task is completed.

The async function returns immediately without waiting for the task to complete. Therefore, the asynchronous function does not block the current thread.

Note: Don't be confused when you read that the synchronization function is blocking (block) The current process or the function is a blocking (blocking) function! The verb blocking (block) describes the effect of the function on the current thread, which is not related to blocks. Also remember that the block in the GCD document about OC can be swapped with Swift's closure.

Critical area (Critical section)

This is a piece of code that cannot be executed concurrently, meaning that two threads cannot execute it at the same time. This is usually because the code modifies the shared resource. Otherwise, concurrent processes that modify the same variable at the same time cause an error.

Race condition

When two threads compete for the same resource, a race condition is called if the order of access to the resource is sensitive. Race conditions can produce unpredictable behavior that is not easily detected during code inspection.

Dead lock

The dilemma that two or more threads are trapped by waiting for each other to complete is called a deadlock. The first thread cannot be completed because it is waiting for the second thread to finish. But the second thread cannot finish because it waits for the first thread to finish.

Thread Safety

Thread-Safe code can be safely called by multiple threads or concurrent tasks, and he will not cause any problems (data errors, crashes, etc.). Non-thread-safe code can only be executed on its own at the same time. A thread-safe code such as let A = ["Thread-safe"]. Because the array is read-only, it can be used by multiple threads at the same time without causing problems. On the other hand, var a = ["Thread-unsafe"] is a mutable array. This means that it is not thread-safe, because multiple threads can fetch and modify the array at the same time, resulting in unpredictable results. Non-thread-safe variables and mutable data structures should only be fetched by one thread at a time.

Context Switches

Context switching is the process of saving and recovering a program's execution state while switching between different threads in a process. This process is quite common when writing multitasking apps, but it can cause some extra expense.

Concurrency vs Parallel

Concurrency and parallelism are often raised simultaneously, so it is worthwhile to differentiate each other by a short explanation.

A separate part of the concurrent code can be executed concurrently. However, it is up to the system to determine how concurrency occurs or whether it occurs.

Multi-core devices execute multiple threads concurrently, but in a single-core device, another thread or process must be run through a context switch. This process usually happens so quickly that it gives the illusion of parallelism.

Queue

GCD provides scheduling queues (dispatch queues) to handle submitted tasks, which manage the tasks that you submit to the GCD and perform the tasks in first in, in, Out (FIFO) order. This ensures that the first task that joins the queue is executed first, the second one is executed, and so on.

All scheduling queues are thread-safe so that you can use them in multiple threads at the same time. When you understand how the dispatch queue provides thread safety for your code, the benefits of GCD are obvious. The key is to choose the right scheduling queue type and the correct dispatch function (dispatching functions) to submit your task.

Sequential queue

Tasks in the sequential queue perform only one task at a time, and each task starts only after the previous task has completed. At the same time, you do not know the interval between when a task is completed and the start of another task

The execution of the task is under the control of GCD; the only thing you know for sure is that GCD executes only one task at a time and executes in the order in which the task joins the queue.

Because no two tasks are performed concurrently in the sequential queue, there is no risk of multiple tasks entering the critical section at the same time, which guarantees that the critical section will not have a race condition. Therefore, if the only way to enter the critical section is by submitting the task to the dispatch queue, then the critical section can be secured.

Tasks in the concurrent queue are guaranteed to be executed in the order of entry queues ... Just that! Tasks can be done in any order and you don't know when the next task will start or how many tasks are running at any one time. Once again, it all depends on GCD. Shows an example of four concurrent tasks:

When to start a task depends entirely on GCD. If the execution time of one task overlaps with another, it is up to GCD to decide whether to run the task on another available kernel or to run another program through context switching.

First, the system provides a special sequential queue of main queues. As with other sequential queues, only one of the tasks in this queue is executing at the same time. However, this queue ensures that all tasks are executed in the main thread, which is the only thread that allows the UI to be updated. This queue is used to send messages or send notifications to UIView objects.

The system also provides several concurrent queues. These queues are related to their own QoS levels. The QoS level represents the intent to commit the task, allowing GCD to decide how to prioritize.

    • The Qos_class_user_interactive:user INTERACTIVE level indicates that the task needs to be executed immediately to provide a good user experience. Use it to update the UI, respond to events, and require low-latency small workload tasks. This level of work should be kept to a smaller scale.

    • The Qos_class_user_initiated:user initiated level indicates that the task is initiated by the UI and can be executed asynchronously. It should be used in tasks where the user needs immediate results and requires the ability to continue interacting.

    • The qos_class_utility:utility level represents a long-running task, often accompanied by a progress indicator that is visible to the user. Use it to do tasks such as computing, I/O, networking, continuous data filling, and so on. This grade is designed to be energy efficient.

    • The Qos_class_background:background level represents tasks that users will not notice. Use it to perform preload, maintenance, or other tasks that do not require user interaction and are insensitive to time.

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.