iOS Core notes-multi-threaded-GCD

Source: Internet
Author: User
Tags gcd

1, GCD Introduction:

?了解: GCD is all called "Grand Central Dispatch", pure C language, GCD provides a lot of powerful functions, GCD all the functions are contained in the Libdispatch library.

1-1, the advantage of using GCD:

?了解: 1, GCD is the Apple company for multi-core parallel operation proposed solution;

?了解: 2, GCD will automatically take advantage of more CPU cores (for example: dual-core, quad-core);

?了解: 3. GCD automatically manages the life cycle of threads (creating threads, scheduling tasks, destroying threads).

1-2, gcd two core concepts:
name function:
任务 What action to take
队列 Used to store tasks
1-3, gcd use steps:
steps: function:
?步骤一定制任务 Identify the things you want to do
?步骤二将任务添加到队列中 GCD will automatically take the tasks in the queue and put them in the corresponding thread.
2. gcd function and queue: 2-1, function of GCD Package task:
name function:
?重要: Sync function ( dispatch_sync() ) The ability to open a new thread is not available, and the task encapsulated in the synchronization function needs to be executed immediately in the current thread, that is, when a synchronization function is used to encapsulate multiple tasks in the current thread, the block in the synchronization function is immediately executed every time the synchronization functions are executed.
?重要: Async function ( dispatch_async() ) With the ability to turn on threads, you can open new threads. When an asynchronous function encapsulates a task, if there are multiple tasks that need to be added to the same queue, it will wait until all tasks are added to the queue before the task execution is removed from the queue.
2-2. GCD queue:
name function:
Serial queue The tasks in the queue must be executed sequentially. That is, the current task is removed from the queue and must be completed before the next task can be taken out of the queue. Note: The tasks in the serial queue need to be executed immediately in the current thread.
Concurrent queues Multiple tasks can be executed concurrently, only in the asynchronous function to execute the task concurrently, that is: in the asynchronous function, from the concurrent queue when the current task is removed, you can immediately remove the next task, do not wait for the currently taken out of the task to complete the second task can then be taken out, The combination of asynchronous functions enables multiple tasks to be put into multiple threads and executed concurrently. Note: When multiple tasks are required for concurrent queues, it is necessary to wait for all tasks to be added to the queue to begin the task.
Primary queue A special serial queue associated with the main line threads, with dispatch_get_main_queue()函数 no parameters; Note: The tasks in the master queue must be executed in the main thread and only the task execution in the main queue is fetched when the primary thread is idle.
Global concurrent queues Global concurrent queues dispatch_get_global_queue()函数 have high priority, default priority, low priority, and background priority with a total of four types of global concurrent queues that can be obtained by default in the entire application, and we just choose one of them to take directly. Instead, creating a concurrent queue manually using the CREATE function starts from scratch to create a new concurrent queue.

?备注: Whether it is a serial queue, a concurrent queue, a global concurrent queue, or a home row, the task in the queue is taken out of the FIFO principle: first-in, LIFO, and backward-out.

2-3, each queue acquisition method: 1, serial queue ( DISPATCH_QUEUE_SERIAL):

1./* 参数说明
2. *
3. * 第一个参数:C语言的字符串 给队列起个名字(建议:com.hhf.www.DownloadQueue)
4. * 第二个参数:队列类型
5. * DISPATCH_QUEUE_CONCURRENT 并发队列
6. * DISPATCH_QUEUE_SERIAL 串行队列
7. */
8. dispatch_queue_t queue = dispatch_queue_create("com.hhf.www.DownloadQueue", DISPATCH_QUEUE_SERIAL);
9.
2. Concurrent Queue ( DISPATCH_QUEUE_CONCURRENT):

1./* 参数说明
2. *
3. * 第一个参数:C语言的字符串 给队列起个名字(建议:com.hhf.www.DownloadQueue)
4. * 第二个参数:类型
5. * DISPATCH_QUEUE_CONCURRENT 并发队列
6. * DISPATCH_QUEUE_SERIAL 串行队列
7. */
8. dispatch_queue_t queue = dispatch_queue_create("com.hhf.www.DownloadQueue", DISPATCH_QUEUE_CONCURRENT);
3. Home row:

1.  // 1. 获取主队列
2. dispatch_queue_t queue = dispatch_get_main_queue();
4. Global Concurrency queue:

1.// 1. 获取全局并发队列
2./* 参数说明
3. *
4. * 第一个参数: 全局并发队列优先级
5. * 第二个参数: 苹果预留参数, 传入0即可
6. * /
7. dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

?备注: There are four global concurrent queues with high priority, default priority, low priority, and background priority, depending on the queue priority level.

as shown in the following:

3, gcd function and queue a variety of combination modes: 3-1, function and queue combination mode:
Combination: Notes
同步函数+串行队列 No child threads are turned on, and all tasks are executed serially in the current thread (i.e.: 任务按顺序执行 )
同步函数+并发队列 No child threads are turned on, and all tasks are executed serially in the current thread (i.e.: 任务按顺序执行 )
异步函数+串行队列 A thread is opened, and all tasks are executed serially in that child thread (i.e.: 任务按顺序执行 )
异步函数+并发队列 A multi-threaded thread is turned on 所有的任务并发执行 ; ?重要 : The number of child threads is not determined by the number of tasks, but is determined automatically by the GCD internal, and GCD thinks that several threads will be opened if a few thread is appropriate.
同步函数+主队列(当前线程:主线程) Deadlock, because the home queue needs to wait for the main thread to be idle, and the task in the synchronization function needs to be executed immediately in the current thread, while the main thread is executing the synchronization function, only after the synchronization function has finished executing the tasks in the main queues; If the current thread is a sub-thread and the primary thread is idle, no deadlock occurs
异步函数+主队列 Does not open a new thread, all tasks are executed serially in the main thread
3-2. Example of combination mode: 1, synchronous function + Serial queue:
1./**
2. 同步函数 + 串行队列: 不会开启新的线程, 任务串行执行
3. */
4.- (void)synSerial{
5. // 1. 创建串行队列
6. dispatch_queue_t queue = dispatch_queue_create("串行队列", DISPATCH_QUEUE_SERIAL);
7. // 2. 同步函数中执行任务
8. dispatch_sync(queue, ^{
9. NSLog(@"1: %@", [NSThread currentThread]);
10. });
11.
12. dispatch_sync(queue, ^{
13. NSLog(@"2: %@", [NSThread currentThread]);
14. });
15.
16. dispatch_sync(queue, ^{
17. NSLog(@"3: %@", [NSThread currentThread]);
18. });
19.}

?分析: Because the synchronization function encapsulates the task and the task is stored in the serial queue, the task is executed sequentially in the current thread, that is, the current thread execution, 任务一 print "1" 任务二 .

2. Synchronization function + Concurrent queue:
1./**
2. 同步函数 + 并发队列: 不会开启新的线程, 并发队列中所有任务按顺序在当前线程中执行
3. */
4.- (void)synConcurrent{
5. // 1. 获取全局并发队列
6. dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
7.
8. // 2. 在同步函数中执行任务
9. dispatch_sync(queue, ^{
10. NSLog(@"1: %@", [NSThread currentThread]);
11. });
12.
13. dispatch_sync(queue, ^{
14. NSLog(@"2: %@", [NSThread currentThread]);
15. });
16.
17. dispatch_sync(queue, ^{
18. NSLog(@"3: %@", [NSThread currentThread]);
19. });
20.}

?分析: Because the wrapper function is a synchronous function, the new thread is not opened, although a concurrent queue is used, but only one thread, and the thread execution task is serial, so all tasks are executed one after the other in order.

3. Asynchronous function + Serial queue:
1./**
2. 异步函数 + 串行队列: 只能开启一条新的子线程, 任务只能在当前子线程中一个接着一个按顺序执行
3. */
4.- (void)asynSerial{
5. // 1. 创建串行队列, 串行队列只能手动创建(主队列也是特殊的串行队列)
6. dispatch_queue_t queue = dispatch_queue_create("HH", DISPATCH_QUEUE_SERIAL);
7.
8. // 2. 异步函数执行任务
9. dispatch_async(queue, ^{
10. NSLog(@"%@", [NSThread currentThread]);
11. });
12.
13. dispatch_async(queue, ^{
14. NSLog(@"%@", [NSThread currentThread]);
15. });
16.
17. dispatch_async(queue, ^{
18. NSLog(@"%@", [NSThread currentThread]);
19. });
20.
21. NSLog(@"---- end ----");
22.}

?分析: Because the encapsulation function is an asynchronous function, a new thread is opened, and the task is added to the serial queue, so that when all tasks are added to the serial queue, the task is executed one at a time (Async function: Causes the need to wait for all tasks to be added to the queue to execute, Serial queue: The task executes sequentially).

4. Asynchronous function + Concurrent queue:
1./**
2. 异步函数 + 并发队列: 开启多条新线程, 任务并发执行
3. */
4.- (void)asynConcurrent{
5. // 1. 获取并发队列两种方式: ①获取全局并发队列; ②手动创建并发队列
6. // long identifier : 队列优先级 ; unsigned long flags : 苹果预留参数
7.// dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
8. dispatch_queue_t queue = dispatch_queue_create("HH", DISPATCH_QUEUE_CONCURRENT);
9.
10. // 2. 使用异步函数执行队列中的任务
11. dispatch_async(queue, ^{
12. NSLog(@"%@", [NSThread currentThread]);
13. });
14.
15. dispatch_async(queue, ^{
16. NSLog(@"%@", [NSThread currentThread]);
17. });
18.
19. dispatch_async(queue, ^{
20. NSLog(@"%@", [NSThread currentThread]);
21. });
22.
23. NSLog(@"--- end ---");
24.}

?分析: Asynchronous function so the multi-threaded thread is turned on, and the concurrent queue can take the task out of the corresponding sub-thread and immediately take the next task out of the queue and put it into the new child thread; However, the task is performed because the async function must wait until all tasks are added to the queue.

5. Sync function + Home column:
1./**
2. 同步函数 + 主队列: 在主线程使用同步函数执行主队列中的任务造成循环等待
3. */
4.- (void)synMainQueue{
5. // 1. 获取主队列
6. dispatch_queue_t queue = dispatch_get_main_queue();
7.
8. // 2. 在同步函数中执行任务
9. dispatch_sync(queue, ^{
10. NSLog(@"%@", [NSThread currentThread]);
11. });
12.
13. NSLog(@"--- end ---");
14.}

?分析: The primary queue is characterized by that the tasks in the master queue must be executed in the main thread. Depending on the thread of the current task, there are two execution results: the main thread and the Home ①当前线程为主线程 column loop wait for the deadlock, because the synchronization function of the current encapsulated task is executed in the main thread (that is, the function is in the dispatch_sync() main thread), and the task encapsulated by the synchronization function must be executed immediately in the current thread; The task that the synchronization function encapsulates is added to the primary queue, and the task in the primary queue is scheduled only by the main thread while waiting for the main thread to be idle, but the main thread is executing the synchronization function at this time, and the task in the synchronization function is not scheduled to cause the synchronization function to not complete, so the main thread is always busy ; that is: The main thread waits for the synchronization function to complete, while the synchronization function waits for the main thread to dispatch the task that it encapsulates into the main queue, while the home row waits for the main thread to be idle, thus causing: 主线程 同步函数 主队列中的任务 主线程 ------------------- ②当前线程为子线程: Because the synchronization function executes in a child thread, if the main thread is idle, it is added to the main queue when the task is encapsulated in a child thread, and the main thread is idle, and the tasks added to the primary queue in the child threads are obtained 主线程的调度执行 , so the synchronization function can be executed without causing a deadlock.

6. Sync function + Home column:
1./**
2. 异步函数 + 主队列: 不会开启新线程, 任务串行执行
3. */
4.- (void)asynMainQueue{
5. // 1. 获取主队列
6. dispatch_queue_t queue = dispatch_get_main_queue();
7.
8. // 2. 在异步函数中执行任务
9. dispatch_async(queue, ^{
10. NSLog(@"%@", [NSThread currentThread]);
11. });
12.
13. dispatch_async(queue, ^{
14. NSLog(@"%@", [NSThread currentThread]);
15. });
16.
17. dispatch_async(queue, ^{
18. NSLog(@"%@", [NSThread currentThread]);
19. });
20.}

?分析: All tasks can be executed in the main thread, regardless of whether the main thread is idle. Because the task is currently encapsulated with an asynchronous function, all tasks need to be added to the primary queue before the main thread can be scheduled for execution. Assuming that the current thread is the main path, when all the tasks are added to the main queue, and the asynchronous function finishes executing, the main threads are idle, and the tasks in the main queue are scheduled for the main thread.

7. GCD Communication between Threads:

4, Summary: 4-1, GCD and Nsthread comparison:
    • 1, all the code is written together, so that the code is more simple, easy to read and maintain;
    • 2, Nsthread through the @selector to specify the method to execute, code dispersion;
    • 3, GCD through the block to specify the code to execute, the code set;
    • 4, the use of GCD does not need to manage the creation/destruction/reuse of threads, programmers do not care about the life cycle of the thread;
    • 5, if you want to open multiple threads nsthread must instantiate multiple thread objects;
    • 6, Nsthread uses the NSObject classification method realizes the inter-thread communication, GCD uses the block to communicate.
4-2. Differences between global queues & concurrent queues:
    • Global queues are also called global concurrent queues.
    • is the system to facilitate the development of programmers to provide, its performance and 并发队列 consistency
    • Global queue:
      • No Name;
      • Neither MRC & ARC need to consider release;
      • In daily development, it is recommended that you use the global queue.
    • Concurrent queues:
      • Have a name, and NSThread the name attributes function similarly;
      • If the MRC is developed, it is necessary to dispatch_release(q); release the appropriate object;
      • When developing a third-party framework, it is recommended that you use concurrent queues.
4-3. Global Queue parameters:
    1. Quality of service (Queue priority for task scheduling) before/ios 7.0 is the priority

      • IOS 8.0 (new, temporarily unavailable):

        • QOS_CLASS_USER_INTERACTIVE0x21, user interaction (hoping for the fastest completion-not with too time-consuming operations)
        • QOS_CLASS_USER_INITIATED0x19, user expectations (hope fast, not too time consuming)
        • QOS_CLASS_DEFAULT0x15, default (used for the underlying reset queue, not for programmers)
        • QOS_CLASS_UTILITY0x11, a utility designed to handle time-consuming operations! )
        • QOS_CLASS_BACKGROUND0x09, backstage
        • QOS_CLASS_UNSPECIFIED0x00, not specified, can be adapted with iOS 7.0
      • IOS 7.0:

        • DISPATCH_QUEUE_PRIORITY_HIGH--2, high priority
        • DISPATCH_QUEUE_PRIORITY_DEFAULT--0, default priority
        • DISPATCH_QUEUE_PRIORITY_LOW--(-2), Low priority
        • DISPATCH_QUEUE_PRIORITY_BACKGROUND-Int16_min, background priority
    1. Reserved for future use, should always pass in 0

Conclusion: If you are adapting to IOS 7.0&ios8.0, use the following code:
dispatch_get_global_queue(0, 0);

4-4. Tasks and Queues:
    • Synchronous and asynchronous determine whether to open a new thread (synchronous not open, asynchronous open):

      • Synchronization: Performs a task in the current thread and does not have the ability to open a new thread;
      • Async: Performs a task in a new thread, with the ability to open a new thread.
    • Serial and concurrency determine how tasks are performed:

      • Serial: Once a task is completed, the next task is executed;
      • Concurrency: Multiple tasks are executed concurrently (concurrently).
    • When the task is asynchronous, the queue determines how many threads are opened:

      • Serial queue: Only one line is opened;
      • Concurrent queues: Multiple bars can be opened.

Tasks and Queues :

iOS Core notes-multi-threaded-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.