(55) iOS multi-thread GCD

Source: Internet
Author: User
Tags gcd

GCD, called the Grand Central Dispatch, is a multi-threaded programming solution developed by Apple.


Concepts of processes and threads:

The In-progress program is called a process that is responsible for the memory allocations that the program runs, each of which has its own independent virtual memory space.

A thread is a separate execution path in a process, that is, the main thread, which has a stack of 1 m, which can be executed in a sub-thread (512K stack) for a time-consuming execution path.

TIP: A new thread consumes memory space and CPU events, too many threads can degrade the performance of the system, and multithreading is achieved through CPU time-division multiplexing.

Tip: Multithreading is to perform multiple tasks concurrently, without increasing the efficiency of the execution of a single algorithm itself.


Three multithreaded Technologies in iOS:

1.NSThread

Building a thread is convenient, but managing multiple threads is difficult, but Nsthread's CurrentThread method keeps track of the thread on which the task resides.

2.GCD Grand Central Dispatch (base C-based API), using block to define tasks, recommended.

3.nsoperation/nsoperationqueue uses GCD's set of OC APIs to provide some features that are not easy to implement in GCD.

TIP: It's better to use GCD directly.


The core idea of GCD is to put the operation (block definition Task) into the queue, the queue is characterized by FIFO (first-in-one-out), and the operation is assigned to the CPU for processing when the team is out.

Tip: The queue is not a thread, nor does it represent the corresponding CPU, such as a dual-core CPU, who is allocated to who is idle, and which CPU is not required to be assigned to when the team is out.

The functions of TIP:GCD are all beginning with dispatch, the meaning of Dispatch is dispatch, dispatch.

Tip:nsthread's CurrentThread gets the name and num dictionaries, where num=1 represents the main thread.

"The concept of process synchronization and Asynchrony"

Process synchronization: An operation is not completed and does not return, must be one thing to do, a thing returned to do the next thing.

Process Async: Multiple operations are performed alternately, and the return time of the operation is indeterminate.

"String, parallel queue"

Tip: Sync as sync, async as Async

1. Asynchronous task for serial queues: executes sequentially using a child thread.

Application: The asynchronous task in the serial queue executes sequentially, such as downloading the picture first, then processing it, the two tasks have a definite order, and the order is determined.

/** *  serial queue */-(void) gcddemo1{    dispatch_queue_t q = dispatch_queue_create ("queue<1>", Dispatch_queue_ SERIAL);    for (int i = 0; i < 3; i++) {        dispatch_async (q, ^{            NSLog (@ "%@ i =%d", [Nsthread currentthread],i);//track Current thread 
   
    });    }}
   
The output of the print serial queue shows that the value of I is output from 0 to 2, respectively:

2015-02-16 17:28:11.559 Multithreading Preliminary [1493:119215] <nsthread:0x7986cbb0>{number = 2, name = (null)} i = 02015-02-16 17:28:1 1.559 Multi-Threading preliminary [1493:119215] <nsthread:0x7986cbb0>{number = 2, name = (null)} i = 12015-02-16 17:28:11.559 multithreading Preliminary [1493:1 19215] <nsthread:0x7986cbb0>{number = 2, name = (null)} i = 2

2. Asynchronous tasks for parallel queues: Use multiple child threads to execute out of order, typically with fewer tasks when several threads are open, and some threads open.

Application: A series of asynchronous tasks have no sequencing.

/** *  parallel queue */-(void) gcddemo2{    dispatch_queue_t q = dispatch_queue_create ("queue<2>", Dispatch_queue_ CONCURRENT);        for (int i = 0; i < 3; i++) {        dispatch_async (q, ^{            NSLog (@ "%@ i =%d", [Nsthread currentthread],i);//track Current thread 
   
    });    }    }
   
The printout shows that the values of I are randomly arranged:

2015-02-16 17:28:55.084 Multithreading Preliminary [1521:119972] <nsthread:0x796347d0>{number = 2, name = (null)} i = 22015-02-16 17:28:5 5.084 Multi-Threading preliminary [1521:119975] <nsthread:0x79956380>{number = 3, name = (null)} i = 02015-02-16 17:28:55.084 multithreading Preliminary [1521:1 19973] <nsthread:0x796a2ba0>{number = 4, name = (null)} i = 1

3. Serial Queue Synchronization task: Only use the main thread sequence execution, less useful.

/** *  Serial Queue synchronization task */-(void) gcddemo12{    dispatch_queue_t q = dispatch_queue_create ("queue<1>", Dispatch_ queue_serial);    for (int i = 0; i < 3; i++) {        dispatch_sync (q, ^{            NSLog (@ "%@ i =%d", [Nsthread currentthread],i);//track Current thread        });    }}
2015-02-16 17:33:12.938 Multithreading Preliminary [1574:121669] <nsthread:0x7a25f5a0>{number = 1, name = main} i = 02015-02-16 17:33:12. 938 multi-Threading preliminary [1574:121669] <nsthread:0x7a25f5a0>{number = 1, name = main} i = 12015-02-16 17:33:12.938 multithreading Preliminary [1574:12,166 9] <nsthread:0x7a25f5a0>{number = 1, name = main} i = 2

4. Parallel Queue Synchronization task: Use only the main thread to execute sequentially.

TIP: Serial Queue asynchronous tasks are the most useful, both asynchronous and sequential .

TIP: If you first add an asynchronous task to the queue and then join the synchronization task, the synchronization task will run in the asynchronous task.

TIP: Parallel queues are difficult to control the execution order and maximum number of concurrent, error-prone.


5. The role of the thread name: After the break point, you can see the thread name on the left.

TIP: You can also get CPU usage per thread by clicking on the running state of the CPU.


6. Do not forget to write Dispatch_release (q) When developing non-arc;

"Global Queue"

Apple provides for all apps to work together, and it's a special parallel queue .

Using Dispatch_get_global_queue get, the first parameter is priority, by the right prompt input, the second is for later use, passed in 0.

Difference from parallel queue: No need to create, name starts with Com.apple.

Disadvantage: You cannot get the exact queue name when debugging.

"Main thread Queue"

Note: iOS can only update the UI on the main thread, so actions related to UI updates should be performed on the main thread, which is a special serial queue .

Get using the Dispatch_get_main_queue () function.

Difference from serial queue: No need to create, name starts with Com.apple.

"Process blocking"

Note that the main thread is always working, unless the program is killed, or the main thread's work will never end.

Because the synchronization task waits for the previous task, joining the synchronization task in the main thread causes the process to block.

TIP: only asynchronous tasks can be added to the main thread.

Summary

1. Concurrent programming encapsulates multithreaded programming without the need to care about thread creation and recycling, in order to get programmers out of the complex line-control process, just to face queues and tasks.

2. Note that the priority of the queue is always write Dispatch_queue_priority_default, the priority error causes the priority reversal, the low priority thread may block the high priority thread, and for the sake of insurance, the asynchronous task of serial queue should be used.

3. Synchronizing task nesting synchronization tasks can cause blocking because the first task completes after the second task is completed, and the second completes after the first task executes, so the two wait for each other and cannot end.

The 4.GCD queue has 5 priority levels, from high to Main->high->default->low->background, and then four to the GCD thread pool, and the highest level is the main thread.

(55) iOS multi-thread 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.