IOS advanced learning-multithreading and ios advanced multithreading

Source: Internet
Author: User

IOS advanced learning-multithreading and ios advanced multithreading

I. multithreading Overview

1. Programs, processes, threads

  • Program: executable Application Generated by source code. (For example, QQ. app)
  • Process: A running program can be considered as a process. (For example, a running QQ is a process), and the process has all the resources required for independent operation.
  • Thread: A code segment that runs independently in a program. (For example, the Code for receiving QQ messages)
  • A process is composed of one or more threads. The process is only responsible for resource scheduling and allocation. The thread is the real execution unit of the program and is responsible for code execution.

2. Single thread

  • Each running program (process) contains at least one thread, which is called the main thread.
  • The main thread is created when the program is started and used to execute the main function.
  • A program with only one main thread is called a single-threaded program.
  • In a single-threaded program, the main thread is responsible for executing all the code of the Program (UI display and refresh, network requests, local storage, etc ). These codes can only be executed sequentially and cannot be executed concurrently.

3. Multithreading

  • A program with multiple threads is called a multi-threaded program.
  • IOS allows users to open up new threads themselves. These threads are called subthreads as opposed to the main threads.
  • Several sub-threads can be opened as needed
  • The sub-thread and main thread are independent operation units, and their respective operations do not affect each other, so they can be executed concurrently.

4. Differences between single and multi-threading

  • Single-threaded program: there is only one thread, that is, the main thread, code execution in sequence, prone to code blocking (the page is suspended ).
  • Multi-threaded program: multiple threads run independently between threads, which can effectively avoid code blocking and improve program running performance.
  • Note: In iOS, you must add and refresh the UI in the main thread.

Ii. NSThread

One of the methods for implementing multithreading: NSThread, which is a lightweight multithreading. It can be created in either of the following ways:

# Pragma mark-NSThread manually opens sub-thread // parameter 1: target // parameter 2: Method // parameter 3: Passing parameter NSThread * thread = [[NSThread alloc] initWithTarget: self selector: @ selector (sayHi) object: nil]; [thread start]; // use NSThread and NSObject to open the thread, and the system will automatically release the thread, therefore, you do not need to manually close it. // Two methods for terminating a thread // cancel a thread (sending an End message to the thread and canceling the message) [thread cancel]; // terminate the thread immediately [NSThread exit]; # pragma mark-NSThread automatically opens sub-threads // The thread starts automatically // reverses the sequence of manually opened targets and selector [NSThread detachNewThreadSelector: @ selector (sayHi) toTarget: self withObject: nil]; // obtain the NSLog of the current thread (@ "current =%@", [NSThread currentThread]); // obtain the main thread NSLog (@ "mainThread =%@", [NSThread mainThread]); // determine whether the current thread is the main thread NSLog (@ "isMainThread = % d", [NSThread isMainThread]);

In NSObject, there is a simple background execution method:

# Pragma mark-NSObject: one of the ways to enable the Sub-Thread/***: NSObject * // use javasmselectorinbackground to open up the Sub-thread // The first parameter: selector // The second parameter: The parameter passed by the method [self passed mselectorinbackground: @ selector (sayHi) withObject: @ "test"];-(void) sayHi {// return to the main thread // parameter 1: selector // parameter 2: passing the parameter // parameter 3: whether to enter the main thread after the sub-thread is completed [self supplied mselecw.mainthread: @ selector (mainThreadChangeColor) withObject: nil waitUntilDone: YES];}

Iii. NSOperationQueue

1. NSOperation

  • NSOperation class, which belongs to M in MVC, is an abstract class used to encapsulate code and data related to a single task.
  • It is abstract and cannot be used directly. Instead, it uses a subclass (NSInvocationOperation or NSBlockOperation) to execute the actual task.
  • NSOperation (including subclass) is only an operation. It has no main thread or subthread, and can be used in any thread. It is usually used in combination with NSOperationQueue.
  • Note: When NSOperation subclass is used to create a thread, the actual thread is not actually created.

2. NSInvocationOperation

  • NSInvocationOperation is a subclass of NSOperation.
  • The target and action to be executed are encapsulated.
/*** NSOperation cannot be used to create multiple threads directly. You need to use: NSOperationQueue * // use the first subclass of NSOperation to create a sub-thread: NSInvocationOperation * operation = [[NSInvocationOperation alloc] initWithTarget: self selector: @ selector (test) object: nil]; // when using NSOperation subclass to create a thread separately, you must start [operation start];

3. NSBlockOperation

  • NSBlockOperation is a subclass of NSOperation.
  • Encapsulated the code block to be executed
// Use the second NSOperation subclass to create the sub-thread NSBlockOperation * blockOperation = [NSBlockOperation blockOperationWithBlock: ^ {NSLog (@ "I Am a block"); NSLog (@ "------- % @", [NSThread currentThread]); NSLog (@ "********** % @", [NSThread mainThread]);}]; [blockOperation start];
  • The above two threads must be put in the Operation queue to create sub-processes in the real sense.
  • Once the created object is added to the operation queue, the start method cannot be called. Otherwise, the program will crash
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];    [queue addOperation:operation];    [queue addOperation:blockOperation];

4. NSOperationQueue

  • NSOperationQueue is an Operation queue used to manage the execution of a group of Operation objects. It will automatically open up a proper number of threads for Operation as needed to complete parallel execution of tasks.
  • Here, NSOperation can adjust its priority in the queue (use addDependency: Set dependency ).
  • When the maximum concurrency is set to 1, thread synchronization (serial execution) can be implemented ).
// Create a queue object NSOperationQueue * queue = [[NSOperationQueue alloc] init]; // when the value is set to 1, it can be called serial: that is, sequential execution // when the value is greater than 1, it is called parallel: multiple channels simultaneously perform their respective job queue. maxConcurrentOperationCount = 2; for (int I = 0; I <10; I ++) {NSBlockOperation * blockOperation = [NSBlockOperation blockOperationWithBlock: ^ {NSLog (@ "current = % @, da =%@, I = % d ", [NSThread currentThread], [NSThread mainThread], I) ;}]; [queue addOperation: blockOperation];}

Iv. GCD

1. GCD Introduction

  • Grand Central Dispatch (GCD) is a multi-core programming technology developed by Apple. It is mainly used to optimize applications to support multi-core processors and other Symmetric Multi-processing systems.
  • GCD provides functions for multi-threaded development with higher performance and more powerful functions.
  • It is released on Mac OS X 10.6 For the first time, and is also available for iOS 4 and later versions.

2. core concepts of GCD

  • Task: code segment with certain functions. It is generally a block or function.
  • Distribution queue: GCD works as a queue and is FIFO.
  • GCD creates a proper number of threads to execute tasks in the queue based on the distribution queue type.

3. Two queues in GCD (dispatch queue)

  • SerialQueue: Only one task is executed at a time. Serial queue is usually used to synchronously access specific resources or data. When you create multiple Serial queue, although they are executed simultaneously, the Serial queue and Serial queue are executed concurrently. SerialQueue can implement thread synchronization.
# Pragma mark-use GCD to create a serial queue // method 1 provided by the system: dispatch_queue_t queue = dispatch_get_main_queue (); // In real development, if you need to create a serial queue, you are used to this kind of // Second: create yourself // parameter 1: A Macro provided by the system // parameter 2: is the reserved field of the system. // the positions of parameters 1 and 2 can be exchanged. The locations do not strictly require dispatch_queue_t queue = dispatch_queue_create (DISPATCH_QUEUE_SERIAL, 0 );
  • Concurrent: You can execute multiple tasks concurrently, but follow the FIFO rules.
# Pragma mark-use GCD to create a parallel queue // first: the system provides // parameter 1: Priority (there are four, no obvious difference between priority, DISPATCH_QUEUE_PRIORITY_HIGH, DISPATCH_QUEUE_PRIORITY_LOW, required) // parameter 2: system reserved field dispatch_queue_t queue = dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0); // Method 2: self-created // parameter 1: indicates the name of the queue to be created (The Reverse Domain Name is recommended for Apple) // parameter 2: A Macro provided by the system (queue type) dispatch_queue_t queue = dispatch_queue_create ("myQueue ", DISPATCH_QUEUE_CONCURRENT );

4. GCD Functions

  • Dispatch_async () // Add a task to the queue. The task is queued for execution.
  • Dispatch_after () // Add a task to the queue. The task is not only queued, but also executed at a delayed time point.
  • Dispatch_apply () // Add a task to the queue. The task will be executed multiple times.
Dispatch_async (queue, ^ {NSLog (@ "currentThread = % @", [NSThread currentThread]); NSLog (@ "mainThread = % @", [NSThread mainThread]) ;}); dispatch_after (dispatch_time (DISPATCH_TIME_NOW, (int64_t) (3.0 * NSEC_PER_SEC), dispatch_get_main_queue (), ^ {NSLog (@ "output after 3.0 seconds") ;}); dispatch_queue_t queue = dispatch_queue_create ("myQueue", queue); dispatch_apply (10, queue, ^ (size_t index) {NSLog (@ "% ld", index );});
  • Dispatch_group_async () // Add the task to the queue and add the group tag
  • Dispatch_group_notify () // Add the task to the queue. After all the tasks in a group are executed, the task will be executed.
  • Dispatch_barrier_async () // Add the task to the queue. When the task is executed, other tasks are stopped.
// Create a group dispatch_group_t group = dispatch_group_create (); // create a parallel queue dispatch_queue_t queue = dispatch_queue_create (0, queue); dispatch_group_async (group, queue, ^ {NSLog (@ "I am Task 1") ;}); dispatch_group_async (group, queue, ^ {NSLog (@ "I am Task 2 ");}); dispatch_group_async (group, queue, ^ {NSLog (@ "I am Task 3 ");}); // used to listen on the execution status of all tasks (so this function code must be written after all tasks) dispatch_group_policy (group, queue, ^ {NSLog (@ "I executed after all tasks ");});
Dispatch_barrier_async (queue, ^ {
NSLog (@ "I executed ");
});
  • Dispatch_once () not only means that the Code will be run only once, but also thread-safe, this means that you do not need to use such as @ synchronized to prevent non-synchronization when multiple threads or queues are used.
  • Create a singleton using GCD
+ (MyHandle *) sharedMyHandle {// It is executed only once in GCD to record whether the content has been executed static dispatch_once_t onceToken; // ensure that only one dispatch_once (& onceToken, ^ {handle = [[MyHandle alloc] init] ;}); return handle;} is executed concurrently ;}
  • Dispatch_sync () // Add the task to the queue. The block is not executed and the following code is not executed.
  • Differences between async and sync:
// Async does not wait until the block body is executed completely .. Execute the following code // sync. The Code dispatch_queue_t queue = dispatch_get_global_queue (queue, 0); dispatch_sync (queue, ^ {NSLog (@ "first task") ;}); NSLog (@ "Haha"); dispatch_sync (queue, ^ {NSLog (@ "second task") ;}); NSLog (@ "Haha ");
  • Dispatch_async_f () // Add the task to the queue. The task is a non-block function.
// Function void function (void * str) {NSLog (@ "This is a function, % s", str);} // The first parameter: queue // The second parameter: content of the function parameter // third parameter: function dispatch_queue_t queue = dispatch_get_global_queue (queue, 0); dispatch_async_f (queue, @ "passValue", function );

 

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.