() IOS multithreading GCD and ios multithreading gcd

Source: Internet
Author: User

() IOS multithreading GCD and ios multithreading gcd

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


Concepts of processes and threads:

A program in progress is called a process, which is responsible for the memory allocation of the program running. Each process has its own virtual memory space.

A thread is an independent execution path in a process, that is, the main thread. The main thread has a stack area of 1 MB. for time-consuming execution paths, they can be executed in sub-threads (K stack.

Tip: Creating a New thread will consume memory space and CPU events. Too many threads will reduce the running performance of the system. multithreading is implemented through CPU time division multiplexing.

Tip: multithreading is used to execute multiple tasks concurrently without improving the execution efficiency of a single algorithm.


Three multithreading technologies in iOS:

1. NSThread

Creating a thread is convenient, but it is very difficult to manage multiple threads. However, the NSThread currentThread method can track the thread where the task is located.

2. GCD Grand Central Dispatch (based on the underlying API of C language). It is recommended to use block to define tasks.

3. NSOperation/NSOperationQueue uses a set of OC APIs of GCD to provide some features that are not easy to implement in GCD.

Tip: it is better to use GCD directly.


The core idea of GCD is to put operations (block-defined tasks) into the queue. The queue features FIFO (first-in-first-out), and operations are allocated to the CPU for processing when the queue is out.

Tip: the queue is not a thread and does not indicate the corresponding CPU, such as dual-core CPU. It does not need to be concerned about who is allocated to the queue and who is allocated to the CPU when the queue goes out.

Tip: All GCD functions start with dispatch. The meaning of dispatch is dispatch and scheduling.

Tip: The currentThread of NSThread obtains the name and num dictionaries. num = 1 indicates the main thread.

[Process synchronization and Asynchronization]

Process Synchronization: If an operation is not completed, no result is returned. You must do one thing at a time before you can do the next thing.

Asynchronous process: multiple operations are carried out alternately, And the return time of the operation is uncertain.

[String and parallel queue]

Tip: sync and async

1. asynchronous tasks in the serial queue: Run in sequence using a subthread.

Application: asynchronous tasks in the serial queue are executed in sequence, for example, downloading images first and then processing. The two tasks are sorted in a specific 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 ); // trace the current thread });}}
Print the output of the serial queue and find that the I value is output from 0 to 2 respectively:

17:28:11. 559 multithreading preliminary [1493: 119215] <NSThread: 0x7986cbb0> {number = 2, name = (null)} I = 02015-02-16 17:28:11. 559 multithreading preliminary [1493: 119215] <NSThread: 0x7986cbb0> {number = 2, name = (null)} I = 12015-02-16 17:28:11. 559 multithreading preliminary [1493: 119215] <NSThread: 0x7986cbb0> {number = 2, name = (null)} I = 2

2. asynchronous tasks in parallel queue: multiple sub-threads are used for unordered execution. Generally, when there are few tasks, several threads are opened, and some threads are opened when there are many.

Application: A series of asynchronous tasks are not sequential.

/*** 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 ); // trace the current thread });}}
Print the output and find that the I values are randomly arranged:

17:28:55. 084 multithreading preliminary [1521: 119972] <NSThread: 0x796425d0> {number = 2, name = (null)} I = 22015-02-16 17:28:55. 084 multithreading preliminary [1521: 119975] <NSThread: 0x79956380> {number = 3, name = (null)} I = 02015-02-16 17:28:55. 084 multithreading preliminary [1521: 119973] <NSThread: 0x796a2ba0> {number = 4, name = (null)} I = 1

3. Synchronization tasks in the serial queue: only the main thread is used for sequential execution, which is of little use.

/*** Synchronous task of serial queue */-(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 ); // trace the current thread });}}
17:33:12. 938 multithreading preliminary [1574: 121669] <NSThread: 0x7a25f5a0> {number = 1, name = main} I = 02015-02-16 17:33:12. 938 multithreading preliminary [1574: 121669] <NSThread: 0x7a25f5a0> {number = 1, name = main} I = 12015-02-16 17:33:12. 938 multithreading preliminary [1574: 121669] <NSThread: 0x7a25f5a0> {number = 1, name = main} I = 2

4. Synchronization tasks in parallel queue: only the main thread is used for execution in sequence.

Tip: asynchronous tasks in a serial queue are the most useful. They can be executed asynchronously and sequentially.

Tip: if an asynchronous task is first added to the queue and then to the synchronization task, the synchronization task runs in an asynchronous task.

Tip: it is difficult to control the execution sequence and maximum number of concurrent tasks in parallel queues, which is prone to errors.


5. Thread name: the thread name can be viewed on the left after the breakpoint is clicked.

Tip: Click the CPU running status to view the CPU usage of each thread.


6. Do not forget to write dispatch_release (q) during non-ARC development );

Global queue]

Apple provides a special parallel queue for all apps.

Use dispatch_get_global_queue to obtain the parameter. The first parameter is the priority. Enter the parameter at the right of the parameter. The second parameter is for future use. Set the parameter to 0.

Difference from parallel queue: you do not need to create a queue. The name must start with com. apple.

Disadvantage: the queue name cannot be obtained accurately during debugging.

[Main thread queue]

Note: iOS can only update the UI on the main thread. Therefore, operations related to UI update should be performed on the main thread. It is a special serial queue.

Use 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 always works. Unless the program is killed, the work of the main thread will never end.

Because the synchronization task has to wait for the previous Task, adding a synchronization task to the main thread will cause process blocking.

Tip: Only asynchronous tasks can be added to the main thread.

[Summary]

1. concurrent Programming encapsulates multi-threaded programming and does not need to care about thread creation and collection. It is to free programmers from complicated thread control and only need to deal with queues and tasks.

2. note that the queue priority is always set to DISPATCH_QUEUE_PRIORITY_DEFAULT. If a priority error occurs, the priority will be reversed. low-priority threads may block high-priority threads. To be safe, use Asynchronous tasks of serial queues.

3. A nested synchronization task in a synchronization task can cause blocking because the first task is completed only when the second task is completed, the second task is executed on the condition that the first task is completed, so the two wait for each other and cannot end.

4. the GCD queue has five priorities: Main-> High-> Default-> Low-> Background, which are placed in The GCD thread pool, the highest level is the main thread.

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.