GCD of multi-threaded development in iOS

Source: Internet
Author: User
Tags gcd

Overview

GCD the full name is Grand Central Dispatch ( translated as center dispatch queue?) ), can be understood as the thread management queue, is the Apple company for multi-core parallel operation proposed solution , can be based on the system environment Adaptive thread management, basically belongs to fully automatic thread management.

in the GCD inside , tasks need to be executed in the queue, queues are distributed according to their own attributes, but the principle is always FIFO . Queues are divided into serial and parallel queues, the serial queue is only one thread in the queue, so there is only one task in the queue to execute, while parallel will be based on the system environment, automatically adjust the number of threads, can support the simultaneous execution of multiple tasks.

GCD provides methods for creating and acquiring queues, including getting global concurrent queues, serial main thread queues, and creating your own serial queues (why not create concurrency?). Personal understanding is the same as the effect of creating concurrency and directly using global concurrency. Serial queues can perform tasks in order to act as locks, protect shared resources, and data, because they are only capable of performing one task at a time.


Serial Queue
    • Main thread Queue
      Get the main thread queue, live the home row is a serial queue that GCD comes with, and the task for that home column executes on the main thread.
      Gets the serial main thread queue dispatch_queue_t queue = Dispatch_get_main_queue ();//asynchronous Execution of task Dispatch_async (queue, ^{            NSLog (@ "async- %@");        });/ /synchronous Execution of task Dispatch_sync (queue, ^{            NSLog (@ "sync-%@");          });

    • Custom queues
      Create a queue, specify a name, and set the default to dispatch_queue_t queue = Dispatch_queue_create ("My_serial_queue", NULL);//Add Task to queue//If it's not arc, Release the queue dispatch_release (queue);
Concurrent Queues

GCD provides a global concurrency queue for the entire app to use without having to create it yourself

GCD provides a global concurrency queue for the entire application to use, do not need to create//Get global concurrent queue, can choose priority//#define DISPATCH_QUEUE_PRIORITY_HIGH         2//#define Dispatch_ Queue_priority_default      0//#define Dispatch_queue_priority_low          ( -2)//#define Dispatch_queue_priority_ BACKGROUND   int16_mindispatch_queue_t queue = dispatch_get_global_queue (Dispatch_queue_priority_default, 0);// Synchronous execution of the block task Dispatch_async (queue, ^{        NSLog (@ "sync-%@");    /asynchronous execution of block task Dispatch_async (queue, ^{        NSLog (@ "async-%@");    }); /asynchronous Execution Method task Dispatch_async_f (queue, queue_f);

List of main functions
Perform tasks synchronously Blockdispatch_sync (dispatch_queue_t queue, dispatch_block_t block);//Perform Tasks asynchronously Blockdispatch_async ( dispatch_queue_t queue, dispatch_block_t block);//Async-Execute program-defined method void Dispatch_async_f (dispatch_queue_t queue, void * Context, dispatch_function_t work);//create serial thread queue dispatch_queue_t  dispatch_queue_create (const char *label,  dispatch_queue_attr_t attr);//manual release queue void Dispatch_release (dispatch_object_t object);//Get serial main thread queue dispatch_queue_t Dispatch_get_main_queue (void);//Get global concurrent queue dispatch_queue_t dispatch_get_global_queue (long identifier, unsigned long f lags);//Gets the current code of the dispatch queue dispatch_queue_t dispatch_get_current_queue (void);//delay asynchronous execution of block, corresponding to a function dispatch_after_fvoid Dispatch_after (dispatch_time_t when, dispatch_queue_t queue, dispatch_block_t block);//Create a queue group dispatch_group_t Dispatch_group_create (void);

code Example
  • Custom Serial Queue
    -(void) viewdidload{    [Super Viewdidload];        Main thread    NSLog (@ "main-%@", [Nsthread CurrentThread]);        Create serial thread queues    dispatch_queue_t queue = dispatch_queue_create ("My_serial", 0);        Asynchronously executes    the task Dispatch_async (queue, ^{        NSLog (@ "async1-%@", [Nsthread CurrentThread]);    });    Synchronous execution    of task Dispatch_sync (queue, ^{        NSLog (@ "sync-%@", [Nsthread CurrentThread]);    });    Asynchronously executes    the task Dispatch_async (queue, ^{        NSLog (@ "async2-%@", [Nsthread CurrentThread]);    });
    Output Results
    2015-01-01 15:00:35.213 gcddemo[10763:14132221] main-<nsthread:0x7fe192e158c0>{number = 1, name = main} 2015-01-01 15:00:35.214 gcddemo[10763:14132356] Async1-<nsthread:0x7fe192d0b5d0>{number = 2, name = (NULL)} 2015-01-01 15:00:35.214 gcddemo[10763:14132221] sync-<nsthread:0x7fe192e158c0>{number = 1, name = main} 2015-01-01 15:00:35.214 gcddemo[10763:14132356] Async2-<nsthread:0x7fe192d0b5d0>{number = 2, name = (NULL)}
    because it is a serial task queue, there is only one thread for the queue, so two asynchronous tasks get the same number of threads as 1, and the synchronization task executes on the main thread, so it gets the same threading information as the mainline information. Also, because sync is before ASYNC2, Asyn waits until the SYN executes.

  • Main thread Queue
    -(void) viewdidload{    [Super Viewdidload];        Main thread    NSLog (@ "main-%@", [Nsthread CurrentThread]);        Create a serial thread queue because the main thread queue needs to be used on other threads    dispatch_queue_t queue = dispatch_queue_create ("My_serial", 0);        Asynchronously executes    a task Dispatch_async (queue,                ^{//Gets the main thread queue        dispatch_queue_t = Dispatch_get_main_queue ();                Synchronous execution        of task Dispatch_sync (queue, ^{            NSLog (@ "sync-%@", [Nsthread CurrentThread]);        });        Asynchronously executes        the task Dispatch_async (queue, ^{            NSLog (@ "async-%@", [Nsthread CurrentThread])        ;    });}
    Output Results
    2015-01-01 15:29:35.856 gcddemo[10800:14143728] main-<nsthread:0x7ff7d9f0e920>{number = 1, name = main} 2015-01-01 15:29:35.898 gcddemo[10800:14143728] sync-<nsthread:0x7ff7d9f0e920>{number = 1, name = main} 2015-01-01 15:29:35.900 gcddemo[10800:14143728] async-<nsthread:0x7ff7d9f0e920>{number = 1, name = main}
    from the direct result you can see that the thread information obtained is all the same, and is the thread information, because the code is executed in the main thread.

  • Global Queue
    -(void) viewdidload{[Super Viewdidload];        Main thread NSLog (@ "main-%@", [Nsthread CurrentThread]);        Create a serial thread queue because the main thread queue needs to be used on other threads dispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default, 0);        Asynchronously executes the task Dispatch_async (queue, ^{NSLog (@ "async1-started,%@", [Nsthread CurrentThread]);        Sleep (Arc4random ()%10);        NSLog (@ "async1-finished,%@", [Nsthread CurrentThread]);        });        Asynchronously executes the task Dispatch_async (queue, ^{NSLog (@ "async2-started,%@", [Nsthread CurrentThread]);        Sleep (Arc4random ()%10);    NSLog (@ "async2-finished,%@", [Nsthread CurrentThread]);            });        Asynchronously executes the task Dispatch_async (queue, ^{NSLog (@ "async3-started,%@", [Nsthread CurrentThread]);        Sleep (Arc4random ()%10);    NSLog (@ "async3-finished,%@", [Nsthread CurrentThread]);        });        Asynchronously executes the task Dispatch_sync (queue, ^{NSLog (@ "sync-started,%@", [Nsthread CurrentThread]); Sleep (Arc4random ()%10);    NSLog (@ "sync-finished,%@", [Nsthread CurrentThread]); });}
    Output Results
    2015-01-01 15:41:11.802 gcddemo[10851:14149580] main-<nsthread:0x7f9cda427820>{number = 1, name = main} 2015-01-01 15:41:11.803 gcddemo[10851:14149580] sync-started, <nsthread:0x7f9cda427820>{number = 1, name = main} 2015-01-01 15:41:11.803 gcddemo[10851:14149677] async3-started, <nsthread:0x7f9cda624920>{number = 3, name = ( NULL)}2015-01-01 15:41:11.803 gcddemo[10851:14149679] async2-started, <nsthread:0x7f9cda4300c0>{number = 2, name = (null)}2015-01-01 15:41:11.804 gcddemo[10851:14149680] async1-started, <nsthread:0x7f9cda608e80>{number = 4, name = (null)}2015-01-01 15:41:12.809 gcddemo[10851:14149680] async1-finished, <nsthread:0x7f9cda608e80>{ Number = 4, name = (null)}2015-01-01 15:41:13.808 gcddemo[10851:14149679] async2-finished, <nsthread:0x7f9cda4300c0& Gt {Number = 2, name = (null)}2015-01-01 15:41:14.805 gcddemo[10851:14149580] sync-finished, <nsthread:0x7f9cda427820& Gt {Number = 1, name = main}
    from the execution result can be three asynchronous parts of the code of the Nunber are different, and these are executed at the same time, the description is executed at the same time, the synchronization of the thread information and the main thread information is the same.

GCD of multi-threaded development 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.