Introduction to GCD (task, queue) and iosgcd in iOS (50) multi-thread Network

Source: Internet
Author: User

Introduction to GCD (task, queue) and iosgcd in iOS (50) multi-thread Network

CAT/CAT sharing, must be excellent

For Original Articles, please reprint them. Reprinted Please note: Yan Nai-yu's blog
Http://blog.csdn.net/u013357243? Viewmode = contents

1. What is GCD?

The full name is Grand Central Dispatch"

Pure C language, providing a lot of powerful functions

2. Advantages of GCD

GCD is a solution developed by Apple for multi-core parallel computing

GCD will automatically use more CPU cores (such as dual-core and quad-core)

GCD automatically manages the thread lifecycle (creating threads, scheduling tasks, and destroying threads)

The programmer only needs to tell GCD what task to execute and does not need to write any thread Management Code.

3. Prompt

(1) GCD exists in libdispatch. in the dylib library, this scheduling library contains all the things of GCD, but any IOS program loads this library by default, and the library will be dynamically loaded during the running process, manual import is not required.


Click the + button to import the framework.

(2) GCD is pure C language. Therefore, when writing GCD-related code, we are faced with functions rather than methods.
(3) Most functions in GCD start with dispatch.

Ii. Tasks and queues

There are two core concepts in GCD

(1) task: What operations are performed?

(2) queue: used to store tasks

There are two steps to use GCD.

(1) custom tasks

(2) determine what you want to do

After a task is added to the queue, GCD automatically extracts the task from the queue and puts it in the corresponding thread for execution.

Tip: the removal of tasks follows the FIFO principle of the queue: first-in-first-out, and later-in and later-out.

Execute task

1. There are two functions in GCD used to execute the task.

Note: Submit the parameter (task) on the right to the parameter (Queue) on the left for execution.

(1) execute the task dispatch_sync (dispatch_queue_t queue, dispatch_block_t block) in synchronous mode );

Parameter description:

Queue: queue

Block: Task

(2) execute the task dispatch_async (dispatch_queue_t queue, dispatch_block_t block) in asynchronous mode );

2. Differences between synchronization and Asynchronization

Synchronization: executed in the current thread

Asynchronous: executed in another thread

Queue

1. Queue type

GCD queues can be divided into two types:

(1) Concurrent Dispatch Queue)

Concurrent execution of multiple tasks (automatically enabling multiple threads to execute tasks simultaneously) is only effective under the asynchronous (dispatch_async) function.


2) Serial Queue (Serial Dispatch Queue)

Let the task be executed one by one (after a task is executed, execute the next task)


2) Serial Queue (Serial Dispatch Queue)

Let the task be executed one by one (after a task is executed, execute the next task)

3. Serial queue

There are two methods to obtain serial numbers in GCD.

(1) Use the dispatch_queue_create function to create a serial queue

Dispatch_queue_t dispatch_queue_create (const char * label, dispatch_queue_attr_t attr); // queue name, queue attribute, which can be NULL

Example:

Dispatch_queue_t queue = dispatch_queue_create ("wendingding", NULL); // create

Dispatch_release (queue); // non-ARC queue needs to be released manually

(2) Use the main queue column (queue associated with the main thread)

The main queue is a special serial queue that comes with GCD. All tasks in the main queue are executed in the main thread.

Use dispatch_get_main_queue () to obtain the main queue Column

Example:

Dispatch_queue_t queue = dispatch_get_main_queue ();

4. Concurrent queue

By default, GCD provides a global concurrent queue for the entire application.

Use the dispatch_get_global_queue function to obtain the global concurrent queue.

Dispatch_queue_t dispatch_get_global_queue (dispatch_queue_priority_t priority, unsigned long flags); // this parameter is useless for the moment. Use 0.

Example:

This parameter is left for future use. If it is unavailable for the moment, 0 is passed.
The first parameter is the priority. The default parameter is selected here. Obtains a global concurrency queue with the default priority.

Dispatch_queue_t queue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // obtain the global concurrency queue


Note: Priority of global concurrent queues

#define DISPATCH_QUEUE_PRIORITY_HIGH 2 // high

#define DISPATCH_QUEUE_PRIORITY_DEFAULT 0 // default (medium)

#define DISPATCH_QUEUE_PRIORITY_LOW (-2) // low

#define DISPATCH_QUEUE_PRIORITY_BACKGROUND INT16_MIN // background

5. Execution Effects of Various queues

The Code shows that the GCD instance task queue uses an asynchronous function to add tasks to the concurrent queue:
#import "NYViewController.h"

@interface NYViewController ()

@end

@implementation NYViewController

-(void) viewDidLoad
{
     [super viewDidLoad];
     // 1. Get the global concurrent queue
    dispatch_queue_t queue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
     // 2. Add tasks to the queue, you can execute tasks
     // Asynchronous function: Ability to start a new thread
     dispatch_async (queue, ^ {
         NSLog (@ "Download picture 1 ----% @", [NSThread currentThread]);
     });
     dispatch_async (queue, ^ {
         NSLog (@ "Download picture 2 ----% @", [NSThread currentThread]);
     });
     dispatch_async (queue, ^ {
         NSLog (@ "Download picture 2 ----% @", [NSThread currentThread]);
     });
// Print the main thread
     NSLog (@ "主 Thread ----% @", [NSThread mainThread]);

}

@end


Conclusion: Three subthreads are enabled simultaneously.

Add tasks to the serial queue using asynchronous Functions
-(void) viewDidLoad
{
     [super viewDidLoad];

     // Print the main thread
     NSLog (@ "主 Thread ----% @", [NSThread mainThread]);

     // Create a serial queue
     dispatch_queue_t queue = dispatch_queue_create ("wendingding", NULL);
     // The first parameter is the name of the serial queue, which is a C language string
     // The second parameter is the attribute of the queue. Generally speaking, the serial queue does not need to assign any attributes, so it is usually passed NULL

     // 2. Add tasks to the queue for execution
     dispatch_async (queue, ^ {
         NSLog (@ "Download picture 1 ----% @", [NSThread currentThread]);
     });
     dispatch_async (queue, ^ {
         NSLog (@ "Download picture 2 ----% @", [NSThread currentThread]);
     });
     dispatch_async (queue, ^ {
         NSLog (@ "Download picture 2 ----% @", [NSThread currentThread]);
     });

     // 3. Release resources
// dispatch_release (queue);
}


Conclusion: The thread is enabled, but only one thread is enabled.

Use a synchronous function to add tasks to a concurrent queue
/ **
  * Add tasks to the concurrent queue with synchronous functions
  * /
-(void) viewDidLoad
{
     [super viewDidLoad];

     // Print the main thread
     NSLog (@ "主 Thread ----% @", [NSThread mainThread]);

     // Create a serial queue
     dispatch_queue_t queue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);


     // 2. Add tasks to the queue for execution
     dispatch_sync (queue, ^ {
         NSLog (@ "Download picture 1 ----% @", [NSThread currentThread]);
     });
     dispatch_sync (queue, ^ {
         NSLog (@ "Download picture 2 ----% @", [NSThread currentThread]);
     });
     dispatch_sync (queue, ^ {
         NSLog (@ "Download picture 3 ----% @", [NSThread currentThread]);
     });
}


Conclusion: No new threads are enabled, and the concurrent queue loses the concurrent function.

Add a task to a serial queue using a synchronous Function
/ **
  * Add a task to a serial queue with a synchronous function
  * /
-(void) viewDidLoad
{
     [super viewDidLoad];
      NSLog (@ "Add a task to the serial queue with a synchronous function");
     // Print the main thread
     NSLog (@ "主 Thread ----% @", [NSThread mainThread]);

     // Create a serial queue
     dispatch_queue_t queue = dispatch_queue_create ("wendingding", NULL);

     // 2. Add tasks to the queue for execution
     dispatch_sync (queue, ^ {
         NSLog (@ "Download picture 1 ----% @", [NSThread currentThread]);
     });
     dispatch_sync (queue, ^ {
         NSLog (@ "Download picture 2 ----% @", [NSThread currentThread]);
     });
     dispatch_sync (queue, ^ {
         NSLog (@ "Download picture 3 ----% @", [NSThread currentThread]);
     });
}


Conclusion: New threads are not enabled.

Supplement

Supplement: queue name function:

In future debugging, you can see in which queue the task is executed.


Note: Synchronous functions do not have the ability to enable threads. threads are not enabled in any queue. asynchronous functions can enable threads, the number of threads enabled is determined by the queue (only one new thread is enabled for the serial queue and multiple threads are enabled for the concurrent Queue ).

Synchronous Functions

(1) Concurrent queue: no thread is enabled

(2) Serial queue: no thread is enabled

Asynchronous Functions

(1) Concurrent queue: Enabling N threads

(2) Serial queue: enable one thread

Supplement:

All functions with the words "create \ copy \ new \ retain" in their names must be release when this data is not required.
The data type of GCD does not need to be release in the ARC environment.
The data type of CF (core Foundation) still needs to be release in the ARC environment.
Asynchronous functions are capable of thread opening, but do not necessarily enable threads.

G c d needs to be mastered (very important) 1. queue and task

1> task: What operations do you need to perform?
* Use blocks to encapsulate tasks

2> queue: stores tasks
* Global concurrent queue: Allows concurrent task execution

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  • Self-created serial queue: Let the task be executed one by one
dispatch_queue_t queue = dispatch_queue_create("cn.heima.queue", NULL);
  • Main queue: Let the task be executed in the main thread
dispatch_queue_t queue = dispatch_get_main_queue();
2. Function for executing the task

1> synchronous execution: not capable of enabling new threads

dispatch_sync...

2> asynchronous execution: capable of enabling new threads

dispatch_async...
3. Common combinations (master)

1> dispatch_async + global concurrent queue
2> dispatch_async + self-created serial queue

4. Inter-thread communication (master)
dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
    // Perform time-consuming asynchronous operations ...


    dispatch_async (dispatch_get_main_queue (), ^ {
        // Back to the main thread, perform UI refresh operation
    });
}); 
5. All APIs of GCD are in libdispatch. dylib. Xcode will automatically import this library.
  • Main header file: # import
6. delayed execution (master)

1> perform ....
// Automatically return to the current thread after 3 seconds to call self's download: method, and pass the parameter: @ "http://555.jpg"
[Self initialize mselector: @ selector (download :) withObject: @ "http://555.jpg" afterDelay: 3];

2> dispatch_after...
// The queue in which the task is put for execution
Dispatch_queue_t queue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 );
Double delay = 3; // number of seconds delayed
Dispatch_after (dispatch_time (DISPATCH_TIME_NOW, (int64_t) (delay * NSEC_PER_SEC), queue, ^ {
// Task to be executed 3 seconds later
});

7. One-time code (master)

Static dispatch_once_t onceToken;
Dispatch_once (& onceToken, ^ {
// The code above will always be executed once while the program is running
});


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.