Multithreading--GCD

Source: Internet
Author: User
Tags gcd

  • There are 2 core concepts in GCD

    • Task: what action to take
    • Queues: Used to store tasks
  • Perform tasks

    • Synchronization method: Dispatch_sync
      Dispatch_sync (dispatch_queue_t queue, dispatch_block_t block);
      queue:队列block:任务
    • Async method: Dispatch_async
      Dispatch_async (dispatch_queue_t queue, dispatch_block_t block);
    • The difference between synchronous and asynchronous
      • Synchronization: Tasks can only be performed in the current thread, without the ability to open new threads
      • Async: Can perform tasks in a new thread, with the ability to open new threads
  • Queue

    • Concurrent queues
      • Multiple tasks can be executed concurrently (concurrently) (automatic opening of multiple threads concurrently executing tasks)
      • concurrency function is only valid under asynchronous (Dispatch_async) functions
    • Serial queue
      • Let the task execute one after the other (once a task has finished executing, then the next task is performed)
  • Watch out.

    • Primary impact of synchronous and asynchronous: Can I open a new thread
      • Synchronous: Only performs tasks in the current thread, does not have the ability to open new threads
      • Async: Can perform tasks in a new thread, with the ability to open new threads
    • Concurrency and serial primary impact: How tasks are executed
      • Concurrency: Allows multiple tasks to execute concurrently (concurrently)
      • Serial: Once a task is completed, the next task is performed
  • Various task Queue collocation

    • Sync + serial
    • /* synchronous + Serial: does not open a new thread note: If the synchronization function is called, then the subsequent code */-(void ) syncserial{//1 will be executed if the task in the synchronization function is completed. Create a serial queue #define DISPATCH_QUEUE_SERIAL NULL//So you can directly pass null dispatch_queue_t QUEUE = dispatch_queue_create ("Com.520it.lnj"        , NULL);    2. Add the task to the queue Dispatch_sync (queue, ^  {NSLog (@ "Task 1 = =%@" , [Nsthread CurrentThread]);    }); Dispatch_sync (Queue, ^  {NSLog (@ "Task 2 = =%@" , [Nsthread CurrentThread]); Dispatch_sync (Queue, ^{NSLog (@ "Task 3 = =%@" , [Nsthread CurrentThread]);}); NSLog (@ "---------" );}          

       

    • synchronization + concurrency *
      /* synchronization + Concurrency: No new thread homemade */-(void ) syncconcurrent{//1. Create a concurrent queue dispatch_queue_t queue = d        Ispatch_get_global_queue (0, 0 );    2. Add the task to the queue Dispatch_sync (queue, ^  {NSLog (@ "Task 1 = =%@" , [Nsthread CurrentThread]);    }); Dispatch_sync (Queue, ^  {NSLog (@ "Task 2 = =%@" , [Nsthread CurrentThread]); Dispatch_sync (Queue, ^{NSLog (@ "Task 3 = =%@" , [Nsthread CurrentThread]);}); NSLog (@ "---------" );}          

       

    • Asynchronous + serial *
      /* async + Serial: Opens a new thread but only opens a new thread note: If you call an async function, you do not have to wait until the task in the function finishes executing, and then execute the following code */-(void) asynserial{    //1. Creating a serial queue    D ispatch_queue_t queue = dispatch_queue_create ("Com.520it.lnj", dispatch_queue_serial);     /* Reason why you can create a new thread:     We are using the "async" function call to     create only 1 sub-threads:     Our queue is a serial queue     *//    /2. Add a task to the queue    Dispatch_ Async (Queue, ^{        NSLog (@ "Task 1  = =%@", [Nsthread CurrentThread]);    });    Dispatch_async (Queue, ^{        NSLog (@ "Task 2  = =%@", [Nsthread CurrentThread]); Dispatch_async (queue , ^{NSLog (@ "Task 3 = =%@", [Nsthread CurrentThread]);}); NSLog (@ "--------");}        

    • Asynchronous + concurrency *
      /* asynchronous + Concurrency: Opens a new thread if the task is more, it will open multiple threads */-(void) asynconcurrent{/* Perform task Dispatch_async Dispatch_sync *////* First parameter: queue name second parameter: Tell the system to create a A concurrent queue or serial queue dispatch_queue_serial: serial dispatch_queue_concurrent concurrency *//dispatch_queue_t queue = Dispa        Tch_queue_create ("Com.520it.lnj", dispatch_queue_concurrent);          The system has already provided us with a ready-made concurrent queue/* First parameter: IOS8 before is priority, IOS8 is the quality of service iOS8 before *-Dispatch_queue_priority_high     High Priority 2 *-Dispatch_queue_priority_default: Default Priority 0 *-Dispatch_queue_priority_low: Low Priority-2     *-Dispatch_queue_priority_background:ios8 after *-qos_class_user_interactive 0x21 user interaction (the user is eager to perform the task)           *-qos_class_user_initiated 0x19 user needs *-qos_class_default 0x15 default *-qos_class_utility 0X11 tool (Low priority, Apple recommends putting time-consuming operations into this type of queue) *-Qos_class_background 0x09 Backstage *-qos_class_unspecified 0x 00 The second parameter is not set: Waste */dispatch_queue_t queue = dispatch_get_global_queue (0, 0);           /* First parameter: Queue for the task the second parameter: task (block) gcd the task from the queue, follows the FIFO principle, the result of the first-in and out-of-the-box output and the reason that Apple says the principle does not conform: The CPU may dispatch other threads first        Reason to create a new thread: We are using the "async" function call to create multiple child threads: Our queue is a concurrent queue * /dispatch_async (queue, ^{ NSLog (@ "Task 1 = =%@", [Nsthread CurrentThread]);}); Dispatch_async (Queue, ^{NSLog (@ "Task 2 = =%@", [Nsthread CurrentThread]); Dispatch_async (queue, ^{NSLog (@ "Task 3 = =%@", [Nsthread CurrentThread]); });}

    • Async + Home column *
       async +  Home column: Does not create a new thread, and the task is executed in the main thread */-(void ) asyncmain{//Home column://feature: As long as the task is added to the main queue,        Then the task "bound" will be executed in the main thread  whether you are calling a synchronous function or an asynchronous function dispatch_queue_t queue =  dispatch_get_main_queue (); Dispatch_async (Queue, ^  {NSLog (@ "%@" , [Nsthread CurrentThread]),});}       

       

    • Sync + Home Row *
      /* If the sync function + Home column is called in the main thread, the cause of the deadlock is caused by the lock: The sync function is executed in the main thread and waits for the block to complete. The first call to block is added to the home row, and it needs to be executed in the main thread. After calling */-(void) syncmain{    NSLog (@ "%@", [Nsthread CurrentThread]);    Main queue:    dispatch_queue_t queue = dispatch_get_main_queue ();  if the synchronization function is called, then the following code will be executed after the task in the synchronization function is executed    //NOTE: If the Dispatch_sync method is called in the main thread, and the incoming queue is the home column, it will cause a deadlock    Dispatch_sync (Queue, ^{        NSLog (@ "----------");        NSLog (@ "%@", [Nsthread CurrentThread]);}); NSLog (@ "----------");}      

  • GCD Inter-thread communication

Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{    //execute time-consuming asynchronous Operation      ... Dispatch_async (Dispatch_get_main_queue (), ^{        ///Return to main thread, perform UI refresh Operation         })   ;
    • GCD Other uses
    • Delay execution
Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (2.0 * nsec_per_sec)), Dispatch_get_main_queue (), ^{    //2 seconds after executing the code here ...});
    • Disposable code
      • Use the Dispatch_once function to ensure that a piece of code 程序运行过程中 is executed only 1 times




      • });

- 快速迭代
Dispatch_apply (dispatch_get_global_queue (0, 0), ^(size_t index) {    //execute 10 times Code, index Order indeterminate});
    • Barrier (fence)
      • It does not execute until after the execution of the previous task, and the task after it is completed before it executes
      • 不能是全局的并发队列
      • 所有的任务都必须在一个队列中
Dispatch_barrier_async (dispatch_queue_t queue, dispatch_block_t block);

    • Queue Group
dispatch_group_t Group =  dispatch_group_create ();d ispatch_group_async (Group, Dispatch_get_global_queue ( Dispatch_queue_priority_default, 0), ^{    //execute 1 time-consuming asynchronous operations });d Ispatch_group_async (group, dispatch_get_ Global_queue (Dispatch_queue_priority_default, 0), ^{    //execute 1 time-consuming asynchronous operations });d ispatch_group_notify (Group, Dispatch_get_main_queue (), ^{//etc. before the asynchronous operation is complete, return to the main thread ...});     

Multithreading--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.