Oc-19.gcd

Source: Internet
Author: User

Brief introduction
    • GCD (Grand Center Dispatch) is Apple's solution for multi-core parallel computing, pure C language
    • More adaptable to multicore processors and automatic management of thread lifecycles for ease of use
    • GCD multithreading capabilities through tasks and queues

      • Task: Describes the action to be performed
      • Queue: Used to hold the task to be performed, the task in the queue follows the FIFO (first first out) principle
GCD task function (whether to open a new thread)
  • Synchronization

    • does not have the ability to open a new thread
    • Function to perform tasks synchronously

      • void Dispatch_sync (dispatch_queue_t Queue, dispatch_block_t block), block type

        • queue: Task Queue
        • block (code block): task performed
      • Void Dispatch_sync_f (dispatch_queue_t queue, void *context, dispatch_function_t work), function type (each block type corresponds to a Type of function)

        • queue: Task Queue
        • Context: Parameters passed to task function
        • work (function): task performed
    • Other functions that perform the task synchronously (barrier) are executed after the previous task has been executed, and the task behind it executes after it executes

      • void Dispatch_barr Ier_sync (dispatch_queue_t queue, dispatch_block_t block), block type

        • queue: Task queue, which is meaningful only if the parameter is a concurrent queue
      • Dispatch_barrier_sync_f (dispatch_queue_t queue, void *context, dispatch_function_t work), function class Type

  • Asynchronous

    • Ability to open new threads (need to add tasks to concurrent queues)
    • Functions that perform tasks asynchronously (parameter meanings are the same as synchronous functions)

      • void Dispatch_async (dispatch_queue_t queue, dispatch_block_t block)
      • void Dispatch_async_f (dispatch_queue_t queue, void *context, dispatch_function_t work)
    • Other functions that perform the task asynchronously (barrier) are executed before the previous task executes, and the task behind it executes after it executes (the parameter meaning is the same as the synchronization function)

      • void Dispatch_barrier_async (dispatch_queue_t queue, dispatch_block_t block)
      • void Dispatch_barrier_async_f (dispatch_queue_t queue, void *context, dispatch_function_t work)
GCD Queue (how tasks are executed)
    • Concurrent queues

      • Turn on multiple threads to enable multiple tasks in the queue to execute concurrently (mates that require the function to be executed asynchronously)
    • Serial queue

      • The tasks in the queue are executed one by one sequentially
    • Types of queues

      • Serial queue

        • dispatch_queue_t dispatch_queue_create (const char *label, dispatch_queue_attr_t attr)

          • Label: typically 0
          • attr: queue type, dispatch_queue_serial
      • Concurrent queues

        • dispatch_queue_t dispatch_queue_create (const char *label, dispatch_queue_attr_t attr)

          • Label: typically 0
          • attr: Queue type Dispatch_queue_concurrent
      • Primary queue (serial, only running in the main thread)

        • dispatch_queue_t dispatch_get_main_queue (void), gets the home row
      • Global Queue (concurrency)

        • dispatch_queue_t Dispatch_get_global_queue (long identifier, unsigned long flags)
Combination of tasks and queues
  • Synchronization functions

    • Sync function Home Row

      /**- 运行在主线程主队列(未开启新的线程),主线程被卡死- 原因:任务代码等待着当前函数执行完毕才能执行(当前函数正在执行且未执行完毕);   当前函数等待着任务代码 执行完毕才能执行(当前任务正在执行且未执行完毕);   相互等待,出现死锁*///获取主队列dispatch_queue_t queue = dispatch_get_main_queue();//添加任务到队列dispatch_sync(queue, ^{ //任务1代码});dispatch_sync(queue, ^{ //任务2代码});
    • Synchronous function serial queue

       /**-run on the main thread serial non-home column (new thread not opened), Task serial execution */< Span class= "Hljs-comment" >//create serial queue dispatch_queue_t queue = Dispatch_queue_create ( "[email protected]", dispatch_queue_serial); //Add task to queue Dispatch_sync (queue, ^{ //Task 1 code}); Dispatch_sync (queue, ^{//Task 2 code});     
    • Synchronous function Concurrent Queue

      /**- 运行在非主线程并发队列(未开启新的线程),任务串行执行*///获取全局队列(并发)dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);//将任务加至队列dispatch_sync(queue, ^{ //任务1代码});dispatch_sync(queue, ^{ //任务2代码});
  • Asynchronous functions

    • Async function Home column

       /**-run in Main thread host column (new thread not opened), Task serial execution *///get the Home row dispatch_queue_t queue = Dispatch_get_main_queue (); //the task into the queue Dispatch_async (queue, ^{// Task 1 Code});d Ispatch_async (queue, ^{//Task 2 code});    
    • Async function Serial queue

       /**-run in main function serial non-home column (new thread not opened), Task serial execution */< Span class= "Hljs-comment" >//create serial queue dispatch_queue_t queue = Dispatch_queue_create ( "[email protected]", dispatch_queue_serial); //Add task to queue Dispatch_async (queue, ^{ //Task 1 Code}) Dispatch_async (queue, ^{//Task 2 code})    
    • asynchronous function Concurrency queue

      /**- 运行在非主线程并发队列(开启新的线程),任务并发执行- 系统根据任务创建线程(无法确定任务执行在哪个线程)*///获得全局并发队列dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);//将任务加入队列dispatch_async(queue, ^{ //任务1代码});dispatch_async(queue, ^{ //任务2代码});
      Communication between threads
    • From the main thread to the child thread

      • Attention

        • Only the combination of the Async function and the concurrent queue will open the new thread and cause the task to execute concurrently
        • You typically use asynchronous functions to add tasks to a concurrent queue to enable communication from the main thread to the child threads
      • Implementation code

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//需要在子线程中执行的任务代码})
    • From a child thread to the main thread

      • Attention

        • Tasks in the master queue can only be performed in the main thread
        • It is common to use asynchronous/synchronous functions to add tasks to the main queue for communication from child threads to the main thread
      • Implementation code

        dispatch_async(dispatch_get_main_queue(), ^{        //需要在主线程中执行的代码    })
Other tasks of GCD
  • Single execution (usually in the design of singleton mode)

     //define a tag static dispatch_once_t oncetoken; Dispatch_once (&oncetoken, ^{//the code here will only be executed once});      
  • Deferred execution

     /**-method One (GCD) */dispatch_after ( Dispatch_time (Dispatch_time_now, (int64_t) (2.0 * NSEC_PER_ SEC)), Dispatch_get_main_queue (), ^{//the code here will delay execution}); /**-Method II (Performselector) */[self Performselector: @selector (run) withobject:self Afterdelay: 2.0]; /**-method Three (Nstimer) */[nstimer Scheduledtimerwithtimeinterval:2.0 target:self selector:< Span class= "Hljs-keyword" > @selector (run) userinfo:nil repeats: no]              
  • Quick Iteration

     void  Dispatch_apply (size_t iterations, dispatch_queue_t queue, void (^block)  (size_t)) /**iterations: Number of iterations executed queue: Task Queue block: Code for iteration Execution Size_ T: Used to define the current iteration to the number of times, you need to add it yourself, such as adding the index index after size_t, recording the current iteration count */      
  • Barrier

    /**- Barrier中的任务,只能在它前面的任务执行完毕才能执行  Barrier后的任务,只能等到它执行完毕才能执行- 要将队列添加到自己创建的并发队列中,否其功能等同于函数  void dispatch_async(dispatch_queue_t queue, dispatch_block_t block)*///创建队列(通常是自己创建的并发队列)dispatch_queue_t queue = dispatch_queue_create("123", DISPATCH_QUEUE_CONCURRENT);//将任务添加到队列dispatch_async(queue, ^{ //在Barrier前执行的任务代码});dispatch_barrier_async(queue, ^{ //Barrier中的任务代码});dispatch_async(queue, ^{ //在Barrier后执行的任务代码});
  • Queue Group

    //get global concurrency queue dispatch_queue_t  Queue = dispatch_get_global_queue (Dispatch_queue_priority_default, 0); //Create queue Group dispatch_group_t group = Dispatch_group_create (); //Add task to queue Group Dispatch_group_async (group, queue, ^{//Task 1 code});d Ispatch_group_async (group, queue, ^{//Task 2 code});d Ispatch_group_ Notify (group, queue, ^{//task 3 code /** All tasks in the group are executed if group is empty, execute immediately */});        
GCD Timer
  • Implementation principle

    • Creates a Dispatch_source_type_timer type of dispatch source and adds it to the dispatch queue, responding to events by dispatch SOURCE
    • by function void Dispatch_source_set_timer (dispatch_source_t source, dispatch_time_t start, uint64_t interval, uint64_t leeway ) To set the execution event for the dispatch source
  • Implementation code

    Get queuedispatch_queue_t queue = Dispatch_get_main_queue ();Create a TimerSelf. Timer = Dispatch_source_create (Dispatch_source_type_timer,0,0, queue);Set the various properties of the timer (starting and ending time) dispatch_time_t start = Dispatch_time (Dispatch_time_now, (int64_t) (8.0 * nsec_per_sec)); uint64_t interval = (uint64_t) (1.0 * nsec_per_sec);  Set Dispatch_source_set_timer (self. Timer, start, interval, 0);  Set the callback Dispatch_source_set_event_handler (self. Timer, ^{ //Timer to execute code when it is triggered});  Turn on timer dispatch_resume (self. timer);  Cancel Timer dispatch_cancel (self. timer);             

Oc-19.gcd

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.