Easy use of iOS multithreaded GCD

Source: Internet
Author: User
Tags gcd

In iOS development, Apple offers three multithreaded technologies, namely:

(1) Nsthread

(2) Nsoperation

(3) GCD

A brief introduction to the use of GCD.

The GCD full name Grand Central Dispatch, which can be called the Big Center dispatch. In fact GCD is managing a thread pool, how to create threads, how to reclaim threads, and how many threads to allocate, all of which are controlled by GCD. In development, programmers do not need to manipulate the thread of related things, the programmer only need to put the action should be done in the corresponding queue .

One: custom queue

There are multiple queues in gcd, with two custom queues: Serial Queue and parallel queue

1: Serial queue: Tasks in the queue are executed only sequentially, and only one task can be performed at a time. That is, the next task is not performed until a task is completed .

2: Parallel queue: Multiple tasks can be performed at one time. For example, there are 10 tasks in a parallel queue, you can perform 3 tasks at a time, which of the three tasks is executed first, then the remaining tasks are performed.

Note: either serial or parallel queues, they are FIFO (first-out) . That is, regardless of the queue, the sooner the task enters the queue, the sooner it will execute (except in some cases the end time of the task execution is indeterminate).

There are two operations in GCD, namely synchronous and asynchronous operations

1: Synchronous operation: no new thread

2: Asynchronous operation: A new thread is opened

Two operations and two kinds of queues, combined into 4 cases, in fact, in development, some combinations are basically not used. Here are the four combinations described in the program.

Combination one: Serial queue + synchronous operation (no new thread is created, and the task is executed one by one, so it is actually executed sequentially), the code is as follows:

-(void) gcddemo1{    //serial queue + synchronous operation    dispatch_queue_t queue = dispatch_queue_create ("Gcddemo", Dispatch_queue_ SERIAL);    for (int i = 0; i < ++i) {        dispatch_sync (queue, ^{            NSLog (@ "%@%d", [Nsthread currentthread],i);        }}    

Execution Result:

Number = 1, description is the main thread, there is no new thread.

Combination two: Serial queue + asynchronous operation (because the task is executed one by one, but because it is an asynchronous operation, a new thread is opened and all tasks are executed on the new thread), the code is as follows:

-(void  ) gcddemo1{dispatch_queue_t queue /span>= dispatch_queue_create ( gcddemo      , dispatch_queue_serial);  //  serial queue + asynchronous operation  for  (int  i = 0 ; i < 10 ; ++i) {dispatch_async (queue,  ^{NSLog (  @ " %@%d          " ,[nsthread currentthread],i);    }); }}

Execution Result:

Number = 2, which indicates that a new child thread is turned on, but is still executed sequentially.

Combination three: Parallel queue + synchronous operation (because synchronization does not open new threads, even though parallel queues can start multiple tasks at one time, it is still true that each task executes on the main thread and executes sequentially). The code is as follows:

-(void  ) gcddemo2{dispatch_queue_t queue /span>= dispatch_queue_create ( gcddemo      , dispatch_queue_concurrent);  //  parallel queue + Sync task  for  (int  i = 0 ; i < 10 ; ++i) {dispatch_sync (queue,  ^{NSLog ( /span>@ " %@%d   "        ,[nsthread currentthread],i);    }); }}

Execution Result:

No new threads are opened and executed sequentially.

Combination four: Parallel queue + asynchronous operations (parallel queues start multiple tasks at one time, and asynchronous operations can open new threads, so multiple tasks may be executed at the same time, multiple threads are turned on, and the end time for each task is indeterminate). The code is as follows:

-(void  ) gcddemo2{dispatch_queue_t queue /span>= dispatch_queue_create ( gcddemo      , dispatch_queue_concurrent);  //  Parallel queue + Async task  for  (int  i = 0 ; i < 10 ; ++i) {dispatch_async (queue,  ^{NSLog (  @ " %@%d          " ,[nsthread currentthread],i);    }); }}

Execution Result:

As you can see, multiple threads are turned on, and the tasks are not executed sequentially.

Two: Global queue

To facilitate development, Apple also provides a global queue, the global queue is actually a parallel queue, so the results of the global queue execution and the execution of the parallel queue are consistent. The code is as follows:

Global Queue + Sync task:

-(void  ) gcddemo3{dispatch_queue_t queue /span>= Dispatch_get_global_queue (Dispatch_queue_priority_default, 0  );  //  global queue + synchronization task  for  (int  i = 0 ; i < 10 ; ++i) {  Synchronization task  Dispatch_sync (queue, ^{NSLog ( @ " %@%d  "  

Execution Result:

Global Queue + Asynchronous task:

-(void) gcddemo3{    0);     // Global Queue + asynchronous task     for (int0; + +i) {        ^{            NSLog (@ "%@%d  ", [Nsthread currentthread],i);}        );}    }

Execution Result:

Three: Master queue

Apple also provides a queue that is the home row, which is a serial queue, but differs from the serial queue. Tasks on the Home column should be executed sequentially on the main thread, without the concept of asynchrony. That is, even if an asynchronous task executes on the primary queue, the new thread is not opened.

Main Queue + Asynchronous task:

-(void) gcddemo4{    = dispatch_get_main_queue ();     // Home row + asynchronous task     for (int0; + +i) {        dispatch_async (queue,^{            NSLog ( @" %@%d " , [Nsthread currentthread],i);     }}

Execution Result:

As you can see, no new threads are opened and executed sequentially.

The main queue + synchronization task (which blocks threads), the code is as follows:

-(void) gcddemo4{    = dispatch_get_main_queue ();     // the home row + Sync task will block     for (int0; + +i) {        ^{            NSLog (@ "%@%d  ", [Nsthread currentthread],i);}        );}    }

Blocking causes:

The primary queue itself has a task a (the main task), and the task A has not finished executing. In the process of performing task A, a new synchronization task B is inserted. We know that in a serial queue, you must perform one task before you can continue to perform another task. In this case:

If you want to continue with task A, you need to finish the task B, if you want to continue to perform task B, you need to finish the task A, causing the blocking.

In development, this blocking situation should be avoided.

Easy use of iOS multithreaded 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.