Swift's detailed 16-----------GCD Foundation section

Source: Internet
Author: User
Tags gcd


GCD Basic Section


Note: This section focuses on some basic concepts of thread synchronization and the basic part of GCD.



GCD (Grand Central Dispatch)
Let's begin by understanding some of the basic concepts in processing threads:


  • Serial: Only one task can be executed at a time

  • Concurrency: Multiple tasks can be executed simultaneously

  • Synchronization: The synchronization task blocks the current thread, knowing that the task is complete

  • Async: A scheduled task completes but does not wait for it to complete, so an async function does not block the current thread from executing the next function.

  • Critical section: A piece of code cannot be executed concurrently, that is, two threads cannot execute the code at the same time. (different code to manipulate shared resources may deteriorate)

  • Deadlock: Multiple threads are stuck and waiting for the other to complete or perform other operations. The first one cannot be completed because it is waiting for the second one to complete. But the second can't be done, because it's waiting for the first one to finish.

  • Thread Safety: Thread-safe code can be safely called in multi-threaded or concurrent tasks without causing any problems

  • Context switch: A context switch refers to when you switch between individual processes to perform different
    The process of storing and resuming execution state when a thread is running. This process is common when writing multitasking applications, but it brings some extra overhead

  • Concurrency and parallelism: Different parts of concurrent code can be executed "synchronously". Multicore devices execute multiple threads concurrently, in order for a single-core device to do so, they must run a thread, perform a context switch, and then run another thread or process. This usually happens quickly enough to give us the illusion of a concurrent execution.

  • Queues queues: GCD provides dispatch Queues to handle blocks of code that manage the tasks you provide to GCD and perform these tasks in FIFO (first in, in-order) sequence. All dispatch queues (dispatch queues) are thread-safe by themselves, and you can access them in parallel from multiple threads. When you understand how scheduling queues provide thread safety for different parts of your own code, the benefits of GCD are obvious. The key to this is to choose the right type of dispatch queue and the correct dispatch function to submit your work. Because there are not two tasks running concurrently in the serial queue, there is no risk of accessing the critical section at the same time, which, in contrast to these tasks, protects the critical section from the race condition. So if the only way to access a critical section is through the task of committing to the dispatch queue, then you don't need to worry about the security of the critical section.

  • Concurrent Queues Concurrent queues: The tasks in the concurrent queue are guaranteed to be executed in the order in which they were added, but that is all guaranteed. Tasks can be done in any order, and you won't know when to start running the next task, or how many blocks are running at any one time. It all depends on the GCD.
    If the execution time of one Block overlaps another, it is up to the GCD to decide whether to run it on a different core, or, if that core is available, to use the context switch to execute the different blocks.

  • Queue Types Type: First, the system provides you with a special queue called the Home row (main queue). As with other serial queues, the tasks in this queue can only execute one at a time. However, it ensures that all tasks are performed on the main thread, and that the main thread is the only one that can be used to update the UI. This queue is used for messages to UIView or to send notifications.


The system also provides you with several concurrent queues. They are called global dispatch queues (Dispatch Queues). The current four global queues have different priorities: background, low, default, and high. You know, Apple's API also uses these queues, so any tasks you add won't be the only tasks in those queues.



Finally, you can also create your own serial or concurrent queues. This means that at least five queues are at your disposal: The primary queue, the four global dispatch queue, plus any queues you create yourself. GCD's "art" boils down to choosing the right queue to dispatch functions to submit your work.



Here's a look at the example
Global Dispatch Queues


Let back = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
         Let defual = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
         Let high = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
         Let low = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);

         Dispatch_async(back) {
             / / Background execution
         }
         Dispatch_async(defual) {
             / / Background execution
         }
         Dispatch_async(low) {
             / / Background execution
         }
         Dispatch_async(high) {
             / / Background execution
         } 


There are several types of global background execution. Level can be set



Take a look at the main thread below. More to refresh the UI


Dispatch_async(dispatch_get_main_queue()) {
             / / Main thread execution
         } 


User queue


Let queue = dispatch_queue_create("myQueue", nil);
         Dispatch_async(queue) {
             / / Background execution
         } 


Here is the deferred execution


Let time = NSEC_PER_SEC*3
         Let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(time))
         Print(NSEC_PER_SEC)
         Dispatch_after(popTime,dispatch_get_main_queue()) {
             //The content here is executed after 3 seconds.
             Print(2)
         }
         Print(1) 


Here nsec_per_sec = 1000000000
Output after 1 three seconds output 2



Dispatch_once is useful in single-case mode, without the If judgment. Plus this, it's guaranteed to execute only once.


Func onlyOnce(){
         Struct Static {
             Static var onceToken : dispatch_once_t = 0
         }
         Dispatch_once(&Static.onceToken) {
             Print("Only output once"
         }
         Print("Multiple output")
     }


Here the static variable is guaranteed to use the same token


 
 
 
 onlyOnce()
        onlyOnce()
        onlyOnce()
        onlyOnce()
        onlyOnce()

Then we call it multiple times.


Will only output once
Output multiple times
Output multiple times
Output multiple times
Output multiple times
Output multiple times 


The code in Dispatch_once is executed only once.



These are the basic parts of GCD that are summarized today. Next Summary Next Advanced section



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.



Swift's detailed 16-----------GCD Foundation section


Related Article

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.