What is the COMMUNIST Party of China

Second, why do we use COMMUNIST CD technology

Third, in the actual development of how to use GCD to better achieve our needs

  • Synchronous & Asynchronous
  • Serial Queues & Concurrent Queues
  • Global Queues
  • Main Queue Main Queue
  • Five, the role of synchronization

  


What is the COMMUNIST Party of China

GCD is a C-based API that is the marketing name of LibDispatch, an Apple library that enables concurrent code execution on multi-core hardware (iOS or OS X).


Second, why do we use COMMUNIST CD technology

  • GCD can improve the responsiveness of your application by postponing expensive computing tasks and running them in the background.
  • GCD provides an easy-to-use concurrency model that goes beyond locks and threads to help us avoid concurrency traps.
  • GCD has the potential to optimize your code with higher performance primitives on common patterns, such as singletons.
  • GCD is designed to replace threading technologies such as NSThreads
  • The COMMUNIST party can take full advantage of multi-core equipment
  • GCD automatically manages the life cycle of threads

Third, in the actual development of how to use GCD to better achieve our needs

Synchronous & Asynchronous

  1. Synchronous task execution mode: The task is executed in the current thread. The next statement is executed only after the current statement is executed
Start print [NSThread currentThread] print end */ - (void)syncTask { NSLog(@"begin"); ** Parameter 1: DISPATCH_QUEUE_PRIORITY_DEFAULT is the queue priority. For iOS 7.0&8.0, this parameter is always 0. */ dispatch_sync(dispatch_get_global_queue(0, 0), ^{NSLog(@"%@", [NSThread currentThread]); }); NSLog(@"end"); } synchronization methodCopy the code
  1. Asynchronous task execution: The task is not executed in the current thread, and the next statement can be executed without waiting for the completion of the current statement
Pragma mark #pragma mark #pragma mark #pragma mark #pragma mark #pragma mark #pragma mark #pragma mark [NSThread currentThread] */ - (void)asyncTask {/** asyncTask: does not execute on "currentThread". dispatch_async(dispatch_get_global_queue(0, 0), ^{ NSLog(@"%@", [NSThread currentThread]); }); NSLog(@"end"); } asynchronous methodsCopy the code

Serial & Concurrent Queues

  1. Serial queues schedule synchronous and asynchronous task execution

Features of serial queue: Scheduling tasks in queue sequentially in first-in, first-out mode; Regardless of whether the execution task function specified in the queue is synchronous or asynchronous, subsequent tasks are scheduled after the completion of the previous task.

Pragma mark #pragma mark #pragma mark #pragma mark #pragma mark #pragma mark #pragma mark #pragma mark #pragma mark #pragma mark #pragma mark #pragma mark #pragma mark #pragma mark Print order: print from top to bottom, because it is serial 2. On which thread is it executed: */ - (void)serialSync {// 1 */ - (void)serialSync {// 1 Create a serial queue /** Parameter 1: queue representation symbol, Parameter 2: queue type DISPATCH_QUEUE_SERIAL Serial queue DISPATCH_QUEUE_CONCURRENT queue */ dispatch_queue_t serialQuene = dispatch_queue_create("com.baidu", DISPATCH_QUEUE_SERIAL); / / create a task void (^ task1) () = ^ () {NSLog (@ "task1 -- - % @", [NSThread currentThread]); }; void (^task2) () = ^() { NSLog(@"task2---%@", [NSThread currentThread]); }; void (^task3) () = ^() { NSLog(@"task3---%@", [NSThread currentThread]); }; // Add tasks to the queue. Execute dispatch_sync(serialQuene, task1). dispatch_sync(serialQuene, task2); dispatch_sync(serialQuene, task3); } Serial queue synchronization methodCopy the code
Pragma mark #pragma mark - serial queue async method /** Serial queue, async method 1. 2. On which thread: on child threads, because it is asynchronous, asynchronous means it is not executed in the current thread application Scenario: time-consuming, sequential task 1. */ - (void)serialAsync {// It is the same as in the serial synchronization method except for step 3. Create a serial queue dispatch_queue_t serialQuene = dispatch_queue_create("com.baidu", DISPATCH_QUEUE_SERIAL); / / 2. Create a task void (^ task1) = ^ () () {NSLog (@ "task1 -- - % @", [NSThread currentThread]); }; void (^task2)() = ^() { NSLog(@"task2---%@", [NSThread currentThread]); }; void (^task3)() = ^() { NSLog(@"task3---%@", [NSThread currentThread]); }; Dispatch_async (serialQuene, task1); dispatch_async(serialQuene, task2); dispatch_async(serialQuene, task3); } Serial queue asynchronous methodsCopy the code
  1. Concurrent queues schedule asynchronous task execution

Features of concurrent queues: Tasks in queues are scheduled concurrently in first-in, first-out mode. If the current scheduled task is executed synchronously, the system schedules subsequent tasks after the task is executed. If the current scheduled task is executed asynchronously and the underlying thread pool has thread resources available, the new thread will schedule the execution of subsequent tasks

#pragma mark #pragma mark - Concurrent queue synchronization task /** Concurrent queue, synchronization task 1. Print order: because it is synchronous, so execute in sequence 2. Which thread to execute on: The main thread, because it is synchronization method, it is executed in the current thread, also is in the main thread in sequence When encountered a concurrent queue synchronization or executed in sequence, so method (synchronous/asynchronous) priority will be higher than that in the priority queue * as long as it is synchronization method, are carried out only in the current thread, not open the child thread application scenarios: */ - (void)serialSync {/** Parameter 2: queue type DISPATCH_QUEUE_SERIAL Serial queue DISPATCH_QUEUE_CONCURRENT queue */ // 1. Dispatch_queue_t serialSync = dispatch_queue_create("com.xiaojukeji", DISPATCH_QUEUE_CONCURRENT); / / 2. Create a task void (^ task1) = ^ () () {NSLog (@ "task1 -- - % @", [NSThread currentThread]); }; void (^task2)() = ^() { NSLog(@"task2---%@", [NSThread currentThread]); }; void (^task3)() = ^() { NSLog(@"task3---%@", [NSThread currentThread]); }; // 3. Add tasks to the dispatch_sync(serialSync, task1) queue. dispatch_sync(serialSync, task2); dispatch_sync(serialSync, task3); } Concurrent queue synchronization tasksCopy the code
#pragma mark #pragma mark - concurrent queue asynchronous tasks /** 1. Print order: out of order 2. On which thread to execute: It is possible to create N sub-threads, which are determined by the underlying schedulable thread pool. The schedulable thread pool has a reuse mechanism. Application Scenario Downloading multiple movies at the same time */ - (void)serialAsync {// 1. Dispatch_queue_t serialAsync = dispatch_queue_create("com.xiaojukeji", DISPATCH_QUEUE_CONCURRENT); / / 2. Create a task void (^ task1) = ^ () () {NSLog (@ "task1 -- - % @", [NSThread currentThread]); }; void (^task2)() = ^() { NSLog(@"task2---%@", [NSThread currentThread]); }; void (^task3)() = ^() { NSLog(@"task3---%@", [NSThread currentThread]); }; // 3. Add tasks to concurrent queue dispatch_async(serialAsync, task1); dispatch_async(serialAsync, task2); dispatch_async(serialAsync, task3); } Concurrent queue asynchronous tasksCopy the code

Global queue

Global queues are provided by the system for the convenience of programmer development, and their performance is consistent with that of concurrent queues

Global queue vs. concurrent queue

Global queue: no name, whether MRC & ARC does not need to consider release, daily development, recommended to use “global queue “; Concurrent queue: has a name, similar to the name property of NSThread, if MRC development needs to use dispatch_release(q); Release the corresponding object; Dispatch_barrier must use a custom concurrent queue; Concurrent queues are recommended when developing third-party frameworks.

Parameters:

Parameter 1: Quality of service (priority of queue to task scheduling)/ before iOS 7.0, priority iOS 8.0(added, temporarily unavailable, End of this year) QOS_CLASS_USER_INTERACTIVE 0x21, user interaction (expected to complete as soon as possible – no time-consuming operations) QOS_CLASS_USER_INITIATED 0x19, User expectation (expected fast, QOS_CLASS_DEFAULT 0x15, default (used for low-level resetting queues, not programmers) QOS_CLASS_UTILITY 0x11, utility (used for time-consuming operations!) QOS_CLASS_BACKGROUND 0x09, background QOS_CLASS_UNSPECIFIED 0x00 This parameter can be configured 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

Conclusion: For iOS 7.0 & 8.0, use the following code: dispatch_get_global_queue(0, 0);

Pragma mark #pragma mark - Global queue synchronization task /** Global queue, synchronization task 1. Print order: Executed in sequence, because it is synchronous (2) where the thread execution: the main thread, because it is synchronization method, it is in the current thread to perform it When it encounters the synchronization, the concurrent queue or executed in sequence, so method of priority is higher than the priority queue * as long as it is synchronization method, are carried out only in the current thread, */ - (void)globalSync {/** Parameter 1: IOS7: indicates the priority. IOS8: indicates the quality of service. To ensure compatibility with IOS7 and IOS8, 0 is passed. Dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0); / / 2. Create a task void (^ task1) = ^ () () {NSLog (@ "task1 - % @", [NSThread currentThread]); }; void (^task2)() = ^() { NSLog(@"task2----%@", [NSThread currentThread]); }; void (^task3)() = ^() { NSLog(@"task3----%@", [NSThread currentThread]); }; // 3. Add tasks to dispatch_sync(globalQueue, task1); dispatch_sync(globalQueue, task2); dispatch_sync(globalQueue, task3); NSLog(@"end"); } Global queue synchronization tasksCopy the code
#pragma mark #pragma mark - Global queue asynchronous task /** Global queue, asynchronous method 1. Each task is executed on its own thread. The number of threads is determined by the underlying schedulable thread pool. The schedulable thread pool has a reuse mechanism. */ - (void)globalAsync {NSLog(@"begin"); dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0); void (^task1)() = ^() { NSLog(@"task1---%@", [NSThread currentThread]); }; void (^task2)() = ^() { NSLog(@"task2---%@", [NSThread currentThread]); }; void (^task3)() = ^() { NSLog(@"task3---%@", [NSThread currentThread]); }; dispatch_async(globalQueue, task1); dispatch_async(globalQueue, task2); dispatch_async(globalQueue, task3); NSLog(@"end"); } Global queue asynchronous tasksCopy the code

Iv. Main queue

The characteristics of

A queue used to schedule tasks on the main thread

Thread will not be opened

In first-in, first-out mode, tasks in the queue are scheduled to be executed on the main thread only when the main thread is idle

If the main thread is currently running tasks, then whatever tasks are currently added to the main queue will not be scheduled

The queue

The main queue is responsible for scheduling tasks on the main thread

Will be created as the program starts

The main queue only needs to be fetched, not created

Pragma mark #pragma mark #pragma mark #pragma mark #pragma mark #pragma mark #pragma mark #pragma mark #pragma mark Order of execution: execute sequentially, since it is executed in the main thread * seems to conflict with our asynchronous task, but since it is the main queue, execute 2 only in the main thread. */ - (void)mainAsync {NSLog(@"begin"); */ - (void)mainAsync (@"begin"); Dispatch_queue_t mainAsync = dispatch_get_main_queue(); / / 2. Create a task void (^ task1) = ^ () () {NSLog (@ "task1 -- - % @", [NSThread currentThread]); }; void (^task2)() = ^() { NSLog(@"task2---%@", [NSThread currentThread]); }; void (^task3)() = ^() { NSLog(@"task3---%@", [NSThread currentThread]); }; dispatch_async(mainAsync, task1); dispatch_async(mainAsync, task2); dispatch_async(mainAsync, task3); NSLog(@"end"); } Primary queue asynchronous tasksCopy the code
Pragma mark #pragma mark #pragma mark #pragma mark #pragma mark #pragma mark #pragma mark #pragma mark #pragma mark */ - (void)mainSync {NSLog(@"begin"); Dispatch_queue_t mainSync = dispatch_get_main_queue(); / / 2. Create a task void (^ task1) = ^ () () {NSLog (@ "task1 -- - % @", [NSThread currentThread]); }; void (^task2)() = ^() { NSLog(@"task2---%@", [NSThread currentThread]); }; void (^task3)() = ^() { NSLog(@"task3---%@", [NSThread currentThread]); }; // 3. Add dispatch_sync(mainSync, task1) to the main queue. dispatch_sync(mainSync, task2); dispatch_sync(mainSync, task3); NSLog(@"end"); } the main queue synchronization method has a problem, can not use a strange, will cause deadlockCopy the code

Two (and sometimes more) things — in most cases, threads — are stuck and are waiting for the other party to complete or perform another action. The first one doesn’t finish because it’s waiting for the second one to finish. But the second one can’t be completed either, because it’s waiting for the first one to be completed.

Five, the role of synchronization

Synchronization tasks, which can be performed asynchronously by other tasks, depend on a synchronization task. For example, files can be downloaded asynchronously only after the user logs in!

#pragma mark #pragma mark - Simulates login to download multiple movie data /** synchronization function: ensures that our tasks are executed in order 1. */ - (void)loadManyMovie {dispatch_async(dispatch_get_global_queue(0, 0), ^{NSLog(@"%@", [NSThread currentThread]); Dispatch_sync (dispatch_get_global_queue(0, 0), ^{NSLog(@" login --%@", [NSThread currentThread]); sleep(3); }); () dispatch_async(dispatch_get_global_queue(0, 0), ^{NSLog(@" downloading first movie --%@", [NSThread currentThread]); }); Dispatch_async (dispatch_get_global_queue(0, 0), ^{NSLog(@" downloading second movie --%@", [NSThread currentThread]); }); Dispatch_async (dispatch_get_global_queue(0, 0), ^{NSLog(@" downloading third movie --%@", [NSThread currentThread]); }); Dispatch_sync (dispatch_get_main_queue (), ^ {[NSThread sleepForTimeInterval: 1.0]; NSLog(@" computer will shut down in three seconds --%@", [NSThread currentThread]); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{NSLog(@" shutdown --%@", [NSThread currentThread]); }); }); }); } Simulate login to download multiple movie dataCopy the code

This article is from: Serenity _JP

The use of iOS multithreading NSThread

The use of iOS multithreading NSOperation