IOS ----- use GCD for multithreading, and ios ----- gcd for Multithreading

Source: Internet
Author: User

IOS ----- use GCD for multithreading, and ios ----- gcd for Multithreading
Two core concepts of implementing multi-threaded GCD using GCD are as follows:

Queue

The queue is responsible for managing tasks submitted by developers. The GCD queue always processes tasks in FIFO mode-

Because the execution time of the task is different, the task to be processed must be completed first. A queue can process multiple tasks simultaneously in both a serial queue and a concurrent queue. Therefore, multiple tasks are executed concurrently.

The underlying queue maintains a thread pool to process user-submitted tasks. The thread pool is used to execute queue management tasks. Only one thread can be maintained for the underlying thread pool of the serial queue, and multiple threads must be maintained at the underlying layer of the concurrent queue.

Task

A task is the unit of work that the user submits to the queue. These tasks are submitted to the thread pool maintained at the underlying layer of the queue for execution. Therefore, these tasks are executed in multiple threads.

You only need to follow two steps to use GCD.

1.

Create a queue

2.

Submit the task to the queue

     
Create a queue

GCD queues can be divided into two types:

Serial queue

The underlying thread of the serial queue only needs one thread, so only one thread is provided to execute the task. Therefore, the next thread must wait until the execution of the previous task ends before execution can start.

Concurrent queue

The thread pool provides multiple threads to execute tasks. Therefore, you can start and execute multiple concurrent tasks in the FIFO (first-in-first-out) Order.

Function

 

Involves a dispatch_queue_t. This type represents a queue.

The program can create the following Queues:

 

You can use the following code to obtain the default global concurrency queue:

Dispatch_queue_t queue = dispatch_get_global_queue (

DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

You can use the following code to obtain the serial queue associated with the system main thread:

Dispatch_queue_t queue = dispatch_get_main_queue ();

If a task is submitted to a serial queue associated with the main thread, the task is directly executed in the main thread of the program.

You can use the following code to create a serial queue:

Dispatch_queue_t queue = dispatch_queue_create ("LCiOS. queue ",

DISPATCH_QUEUE_SERIAL );

If you submit multiple tasks to the serial queue, multiple tasks can only be executed in order. You must wait until the previous task is completed before you can start to execute the next task.

You can use the following code to create a concurrent queue:

Dispatch_queue_t queue = dispacth_queue_create ("LCiOS. queue"

, DISPATCH_QUEUE_CONCURRENT );

If multiple tasks are submitted to the concurrent queue, the concurrent queue can start multiple concurrent tasks in the FIFO (first-in-first-out) Order. Because the time consumed by the tasks is different, therefore, the task submitted later may be completed first.

After obtaining the queue, you can submit the task to the queue and run the tasks in the thread pool managed by the queue bottom layer.

 

     
Submit tasks Asynchronously

IOS provides the following functions to submit tasks to the queue. Many of the following functions have two versions: one receiving code block is used as the parameter version,

A receiving function is used as the parameter version. The function name of the receiving function as the parameter is suffixed with "_ f", and an additional parameter is used to pass the context defined by the application to the function.

 

Generation

Code

Slice

Segment

1 ViewController. m 2 3 @ implementation ViewController 4 5 // define 2 queues 6 7 dispatch_queue_t serialQueue; 8 9 dispatch_queue_t concurrentQueue; 10 11-(void) viewDidLoad 12 13 {14 15 [super viewDidLoad]; 16 17 // create a serial queue 18 19 serialQueue = dispatch_queue_create ("LCiOS. queue ", DISPATCH_QUEUE_SERIAL); 20 21 // create a concurrent queue 22 23 concurrentQueue = dispatch_queue_create (" LCiOS. queue ", DISPATCH_QUEUE_CONCURRENT); 24 25} 26 27-(IBAction) serial :( id) sender 28 29 {30 31 // submit two code blocks to the serial queue 32 33 // wait until 1st code blocks are completed before 2nd code blocks 34 35 dispatch_async (serialQueue, ^ (void) 36 37 {38 39 for (int I = 0; I <100; I ++) 40 41 {42 43 NSLog (@ "% ===% d", [NSThread currentThread], I); 44 45} 46 47 }); 48 49 dispatch_async (serialQueue, ^ (void) 50 51 {52 53 for (int I = 0; I <100; I ++) 54 55 {56 57 NSLog (@ "% @ ----- % d", [NSThread currentThread], I); 58 59} 60 61 }); 62 63} 64 65-(IBAction) concurrent :( id) sender 66 67 {68 69 // submit two code blocks to the concurrent queue 70 71 // two code blocks can be concurrently executed 72 73 dispatch_async (concurrentQueue, ^ (void) 74 75 {76 77 for (int I = 0; I <100; I ++) 78 79 {80 81 NSLog (@ "% ==== % d ", [NSThread currentThread], I); 82 83} 84 85}); 86 87 dispatch_async (concurrentQueue, ^ (void) 88 89 {90 91 for (int I = 0; I <100; I ++) 92 93 {94 95 NSLog (@ "% @ ----- % d", [NSThread currentThread], I); 96 97} 98 99 }); 100 101} 102 103 @ end

 

Description

Ming

The two lines of the above Code create two queues, of which 1st are serial queues and 2nd are concurrent queues. Next, the program implements the serial: and concurrent: Two event processing methods. In the serial: method, the dispatch_async () function is used to submit two code blocks to the serial queue asynchronously. In the concurrent: use the dispatch_async () function to asynchronously submit two code blocks to the concurrent queue.

Compile and run the program. If you click the button control program to submit two code blocks to the serial queue, the output shown in is displayed on the console.

If

If you click the button control program to submit two code blocks to the concurrent queue, the output shown in

 

Use G

CD download Image

1 ViewController. m 2 3 @ implementation ViewController 4 5-(void) viewDidLoad 6 7 {8 9 [super viewDidLoad]; 10 11} 12 13-(IBAction) downImag :( id) sender14 15 {16 17 // submit the code block to the system's global concurrency queue 18 19 dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ (void) {20 21 NSString * url = @ "route 23 // obtain data from the network 24 25 NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: url]; 26 27 // initialize network data to UIImage object 28 29 UIImage * image = [[UIImage alloc] initWithData: data]; 30 31 if (image! = Nil) 32 33 {34 35 // submit the code block to the queue associated with the main thread. The main thread completes 36 37 dispatch_async (dispatch_get_main_queue (), ^ {38 39 self. iv. image = image; 40 41}); // 142 43} 44 45 else46 47 {48 49 NSLog (@ "--- An error occurred while downloading the image ---"); 50 51} 52 53}); 54 55} 56 57 @ end

 

Description

The code in this program submits the code block to the system's default global concurrent queue, which downloads images from the network. Because the code block is also executed in multiple threads, The dispatch_async () function is used again in code 1 of the program to submit the code of the UI control on the updated interface to the main thread for execution.

Submit tasks synchronously

The dispatch_sync () function will submit the code block in synchronous mode. This function will not return until the code block is executed. if the program uses this function to submit two code blocks (even if it is submitted to the concurrent Queue), it must wait until 1st tasks are completed before it starts to execute 2nd tasks.

For example, some code of the View Controller class in the following example

Generation

Code

Slice

Segment

1 ViewController. m 2 3 @ implementation ViewController 4 5-(void) viewDidLoad 6 7 {8 9 [super viewDidLoad]; 10 11} 12 13-(IBAction) clicked :( id) sender14 15 {16 17 // submit two code blocks in synchronous mode 18 19 dispatch_sync (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ (void) {20 21 for (int I = 0; I <100; I ++) 22 23 {24 25 NSLog (@ "% ===% d", [NSThread currentThread], I ); 26 27 [NSThread sleepForTimeInterval: 0.1]; 28 29} 30 31}); 32 33 // after 1st submitted code blocks are executed, dispatch_sync () the function will return 34 35 // the program will be executed here. Only 2nd code blocks 36 37 dispatch_sync (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ (void) {38 39 for (int I = 0; I <100; I ++) 40 41 {42 43 NSLog (@ "% @ ------ % d", [NSThread currentThread], i); 44 45 [NSThread sleepForTimeInterval: 0.1]; 46 47} 48 49}); 50 51} 52 53 @ end

 

Description

The above program uses the dispatch_sync () function to submit a code block in synchronous mode. This function will return only after the code block is executed. Therefore, although this function starts another thread to execute the code block, but it will still block the main thread.

The above program uses the dispatch_sync () function twice to submit the code block. Therefore, the program must wait until the code block submitted 1st times using the dispatch_sync () function is executed, the program will execute 2nd submissions.

Clicked: The event processing method can only be returned after both submitted code blocks are executed. ---- indicates that the event response execution is complete. if you click the button that fires the event, the button remains highlighted until the execution of the two code blocks is complete.

Tasks executed multiple times

The dispatch_apply () function controls the submitted code block to be executed multiple times. If the code block is submitted to a concurrent queue, the system can use multiple threads to concurrently execute the same code block.

The following example contains a button on the interface. When you click this button, the dispatch_apply () function is used to submit the code block to the concurrent queue and control the code block to be executed multiple times.

The following is the implementation code of the View Controller class in this example.

Generation

Code

Slice

Segment

1 ViewController. m 2 3 @ implementation ViewController 4 5-(void) viewDidLoad 6 7 {8 9 [super viewDidLoad]; 10 11} 12 13-(IBAction) clicked :( id) sender14 15 {16 17 // Control Code Execution 5 times 18 19 dispatch_apply (5, dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) 20 21 // time parameter indicates the number of times 22 23 is being executed currently, ^ (size_t time) 24 25 {26 27 NSLog (=== run [% lu] times ==%@ ", time, [NSThread currentThread]); 28 29}); 30 31} 32 33 @ end

 

Description

The bold code in the above program uses the dispatch_apply () function to control the submitted code block for five times. The code block required by the function is slightly different. The code block can contain a parameter, this parameter indicates the number of times being executed.

 

 

Only one task is executed.

The dispatch_once () function controls the submitted code block to be executed only once throughout the life cycle of the application-only 1st times when the code block is submitted,

This code block will get the execution opportunity. And the dispatch_once () function does not need to be passed into the queue, which means that the system will directly use the main thread to execute the code block submitted by this function.

When executing the dispatch_once () function, you need to input a pointer of the dispatch_once_t type (essentially a long integer) (that is, the predicate parameter ),

This pointer variable is used to determine whether the code block has been executed.

The following example contains a button on the interface. When you click this button, the event processing method triggered will use the dispatch_once () function to submit the code block,

The code block is submitted to the main thread for execution, so the code block may block the main thread. However, when you click the button again, the code block submitted by the dispatch_once () function will not be executed again.

Code snippet

1 ViewController. m 2 3 @ implementation ViewController 4 5-(void) viewDidLoad 6 7 {8 9 [super viewDidLoad]; 10 11} 12 13-(IBAction) clicked :( id) sender14 15 {16 17 static dispatch_once_t onceToken; 18 19 dispatch_once (& onceToken, ^ {20 21 NSLog (@ "= Execution code block = "); 22 23 // thread pause for 3 seconds 24 25 [NSThread sleepForTimeInterval: 3]; 26 27}); 28 29} 30 31 @ end

 

 

 

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.