<span id="Label3"></p><p><p>Can have a copy of the online storage data, for later promotion and reference</p></p><p><p>IOS multithreaded Programming</p></p><p><p>Brief introduction</p></p><p><p>one, <span style="text-decoration: underline;">IOS</span> <span style="text-decoration: underline;">has three kinds of multi-threaded programming technology, respectively:</span></p></p><p><p>1, Nsthread</p></p><p><p>2. Cocoa nsoperation (use of Nsoperation and Nsoperationqueue for iOS multithreaded Programming)</p></p><p><p>3. GCD full name: Grand Central Dispatch (introduction and use of the Grand Central Dispatch for IOS multithreaded Programming)</p></p><p><p>These three ways of programming from top to bottom, the level of abstraction from low to high, the higher the abstraction of the more simple to use, is also the most recommended for Apple.</p></p><p><p>The following main introduction nsthread</p></p><p><p>two, <span style="text-decoration: underline;">Three ways of the advantages and disadvantages of the introduction:</span></p></p><p><p>Nsthread:</p></p><p><p>Pros: Nsthread than the other two lightweight</p></p><p><p>Cons: requires a self-managing thread's life cycle, thread Synchronization. Thread synchronization has a certain overhead in locking data</p></p><p><p>Nsthread implements the following three types of technologies:</p></p><p><p></p></p><p><p>Cocoa Threads</p></p><p><p>POSIX Threads</p></p><p><p>Multiprocessing Services</p></p><p><p></p></p><p><p>General use of Cocoa thread technology</p></p><p><p>Cocoa peration</p></p><p><p></p></p><p><p>Pros: no need to care about thread management, data synchronization, You can focus on what you need to do.</p></p><p><p>Cocoa peration Related class is nsoperation,nsoperationqueue.nsoperation is an abstract class, use it must use its subclass, can implement it or use it to define the two sub-classes:</p></p><p><p>Nsinvocationoperation and Nsblockoperation. Create an object of the Nsoperation subclass and add the object to the Nsoperationqueue queue for Execution.</p></p><p><p>GCD</p></p><p><p>Grand Central Dispatch (GCD) is a solution for multi-core programming developed by Apple. Can only be used after iOS4.0. GCD is an efficient and powerful technology that replaces technologies such as Nsoperation,nsoperationqueue,nsinvocationoperation.</p></p><p><p></p></p><p><p>third, <span style="text-decoration: underline;"></span> <span style="text-decoration: underline;">The use of nsthread:</span></p></p><p><p>There are two direct ways to create 3.1 nsthread:</p></p><p align="left"><p align="left">-(id) initwithtarget: (id) target selector: (SEL) selector object: (id) argument</p></p><p align="left"><p align="left">+ (void) detachnewthreadselector: (SEL) aselector totarget: (id) atarget withobject: (id) anargument</p></p><p><p>The first is an instance method, the second is a class method</p></p><p><p>3.2 The meaning of the parameter:</p></p><p><p>Selector: the method that the thread executes, this selector can only have one parameter, and cannot have the return Value.</p></p><p><p>Target:selector object sent by message</p></p><p><p>Argument: the only parameter transmitted to target, or nil</p></p><p><p>The first way is to create the thread directly and start running the thread, the second way is to create the thread object, and then run the thread operation, you can set the Thread's priority and other thread information before running the thread Operation.</p></p><p><p></p></p><p><p></p></p><p><p>Note: Use threading Notes or recommendations</p></p><p><p>1: when we need to stop the thread halfway, we should not call the exit method, but instead call the Cancel Method. because, If we call the Exit method directly, the thread exits without a chance to perform a cleanup operation, which can result in a memory Leak.</p></p><p><p>2: we have to be clear about such a phenomenon</p></p><p><p>When the thread executes, the thread will be put into hibernation if it is sleepfortimeinterval. Then after it is cancel during hibernation, the fact that the thread wakes up will still perform its operation.</p></p><p><p></p></p><p align="left"><p align="left">Threading Method:</p></p><p align="left"><p align="left"></p></p><p align="left"><p align="left">Thread execution</p></p><p align="left"><p align="left">-(void) threadentrypoint{</p></p><p align="left"><p align="left">@autoreleasepool {</p></p><p align="left"><p align="left">NSLog (@ "Thread Entry point");</p></p><p align="left"><p align="left">While ([[nsthread currentthread] iscancelled] = = NO) {</p></p><p align="left"><p align="left">[nsthread sleepfortimeinterval:10];</p></p><p align="left"><p align="left">NSLog (@ "Thread Loop");</p></p><p align="left"><p align="left">}</p></p><p align="left"><p align="left">NSLog (@ "Thread finished");</p></p><p align="left"><p align="left">}</p></p><p align="left"><p align="left">}</p></p><p align="left"><p align="left"></p></p><p align="left"><p align="left">Stopping a thread</p></p><p align="left"><p align="left">-(void) stopthread{</p></p><p align="left"><p align="left">NSLog (@ "cancelling the Thread");</p></p><p align="left"><p align="left">[self.mythread cancel];</p></p><p align="left"><p align="left">NSLog (@ "releasing the thread");</p></p><p align="left"><p align="left">Self.mythread = nil;</p></p><p align="left"><p align="left">}</p></p><p align="left"><p align="left"></p></p><p align="left"><p align="left">Call:</p></p><p align="left"><p align="left">-(void) viewdidappear: (BOOL) animated{</p></p><p align="left"><p align="left"></p></p><p align="left"><p align="left">Creating Threads</p></p><p align="left"><p align="left">Self.mythread = [[nsthread alloc]</p></p><p align="left"><p align="left">Initwithtarget:self</p></p><p align="left"><p align="left">Selector: @selector (threadentrypoint)</p></p><p align="left"><p align="left">object:nil];</p></p><p align="left"><p align="left"></p></p><p align="left"><p align="left">Open Thread</p></p><p align="left"><p align="left">[self.mythread start];</p></p><p align="left"><p align="left">Let the thread cancel after 3 seconds</p></p><p align="left"><p align="left">[self performselector: @selector (stopthread) Withobject:nil</p></p><p align="left"><p align="left">afterdelay:3.0f];</p></p><p align="left"><p align="left"></p></p><p align="left"><p align="left">}</p></p><p align="left"><p align="left"></p></p><p align="left"><p align="left">Output:</p></p><p align="left"><p align="left"><strong>Thread Entry Point</strong></p></p><p align="left"><p align="left"><strong>Cancelling the Thread</strong></p></p><p align="left"><p align="left"><strong>Releasing the thread</strong></p></p><p align="left"><p align="left"><strong>Thread Loop</strong></p></p><p align="left"><p align="left"><strong>Thread finished</strong></p></p><p align="left"><p align="left"></p></p><p><p>Notice that the red part of the output, I clearly called [nsthread sleepfortimeinterval:10]; method to put the thread into Hibernation. And let the thread have executed the [self.mythread cancel] in the Stopthread method, the method cancels the Thread. however, after the thread is awakened, the following code is executed!</p></p><p><p></p></p><p><p>Improved method: add a layer of judgment!!!</p></p><p><p></p></p><p align="left"><p align="left">-(void) threadentrypoint{</p></p><p align="left"><p align="left">@autoreleasepool {</p></p><p align="left"><p align="left">NSLog (@ "Thread Entry point");</p></p><p align="left"><p align="left">While ([[nsthread currentthread] iscancelled] = = NO) {</p></p><p align="left"><p align="left">[nsthread sleepfortimeinterval:10];</p></p><p align="left"><p align="left">If ([[nsthread currentthread] iscancelled] = = NO) {</p></p><p align="left"><p align="left">To make an improvement, add a layer of judgment in the code that needs to be executed.</p></p><p align="left"><p align="left">NSLog (@ "Thread Loop");</p></p><p align="left"><p align="left">}</p></p><p align="left"><p align="left">}</p></p><p align="left"><p align="left">NSLog (@ "Thread finished");</p></p><p align="left"><p align="left">}</p></p><p align="left"><p align="left">}</p></p><p><p></p></p><p><p></p></p><p><p></p></p><p><p>The use of nsoperation for IOS multithreaded programming</p></p><p><p></p></p><p><p>Nsoperation Introduction</p></p><p><p></p></p><p><p>1. Brief description</p></p><p><p>The role of nsoperation: multi-threaded programming with the use of nsoperation and Nsoperationqueue</p></p><p><p>Nsoperation and nsoperationqueue The specific steps for multithreading:</p></p><p><p>(1) encapsulate the action that needs to be performed into a Nsoperation object first</p></p><p><p>(2) then add the Nsoperation object to the Nsoperationqueue</p></p><p><p>(3) the system will automatically remove the nsoperation from the Nsoperationqueue</p></p><p><p>(4) the operation of the removed Nsoperation package is placed in a new thread to execute</p></p><p><p>2, nsoperation sub-class</p></p><p><p>Nsoperation is an abstract class and does not have the ability to encapsulate operations, it must use its subclasses</p></p><p><p>There are 3 ways to use the Nsoperation subclass:</p></p><p><p>(1) nsinvocationoperation</p></p><p><p>(2) nsblockoperation</p></p><p><p>(3) Customize the subclass inheritance nsoperation, implement the internal corresponding method</p></p><p><p></p></p><p><p>Ii. Specific Instructions</p></p><p><p>1, nsinvocationoperation sub-class</p></p><p><p>creating objects and performing actions</p></p><p align="left"><p align="left">Create an Action object that encapsulates the task to be performed</p></p><p align="left"><p align="left">Nsinvocationoperation Encapsulation operation</p></p><p align="left"><p align="left">Nsinvocationoperation *operation=[[nsinvocationoperation alloc]initwithtarget:self selector: @selector (test) Object : nil];</p></p><p align="left"><p align="left"></p></p><p align="left"><p align="left">Perform actions</p></p><p><p>[operation start];</p></p><p><p></p></p><p><p>Attention</p></p><p><p>The action object is executed by default in the main thread, and only new threads are opened when added to the Queue. That is, by default, if the action is not placed in the queue, it is performed synchronously. Operations are performed asynchronously only if the nsoperation is placed in a nsoperationqueue</p></p><p><p>2, nsblockoperation sub-class</p></p><p><p>creating objects and adding operations</p></p><p><p></p></p><p align="left"><p align="left">Create a Nsblockoperation Action object</p></p><p align="left"><p align="left">Nsblockoperation *operation=[nsblockoperation blockoperationwithblock:^{</p></p><p align="left"><p align="left">NSLog (@ "nsblockoperation------%@", [nsthread currentthread]);</p></p><p align="left"><p align="left">}];</p></p><p align="left"><p align="left">Add action</p></p><p align="left"><p align="left">[operation addexecutionblock:^{</p></p><p align="left"><p align="left">NSLog (@ "NSBlockOperation1------%@", [nsthread currentthread]);</p></p><p align="left"><p align="left">}];</p></p><p align="left"><p align="left">[operation addexecutionblock:^{</p></p><p align="left"><p align="left">NSLog (@ "NSBlockOperation2------%@", [nsthread currentthread]);</p></p><p align="left"><p align="left">}];</p></p><p align="left"><p align="left">Turn on the Execute action</p></p><p><p>[operation start];</p></p><p><p></p></p><p><p>Attention</p></p><p><p>An operation is performed asynchronously as long as the operand of the nsblockoperation package is >1</p></p><p align="left"><p align="left">3.NSOperationQueue</p></p><p align="left"><p align="left">Nsoperationqueue role: nsoperation can be adjusted to start the task, but the default is synchronous execution</p></p><p align="left"><p align="left">If you add nsoperation to the Nsoperationqueue (action queue), The system automatically executes the operations in Nsoperation asynchronously</p></p><p><p>Add actions to nsoperationqueue, automate actions, automatically open threads</p></p><p><p></p></p><p align="left"><p align="left">-(void) Viewdidload</p></p><p align="left"><p align="left">{</p></p><p align="left"><p align="left">[super viewdidload];</p></p><p align="left"><p align="left">Additional setup after loading the view, typically from a nib.</p></p><p align="left"><p align="left">Self.title = @ "test";</p></p><p align="left"><p align="left">Self.view.backgroundColor = [uicolor whitecolor];</p></p><p align="left"><p align="left"></p></p><p align="left"><p align="left"></p></p><p align="left"><p align="left">Creating Nsinvocationoperation objects, Encapsulating operations</p></p><p align="left"><p align="left">Nsinvocationoperation *operation1=[[nsinvocationoperation alloc]initwithtarget:self selector: @selector (test1) object:nil];</p></p><p align="left"><p align="left">Nsinvocationoperation *operation2=[[nsinvocationoperation alloc]initwithtarget:self selector: @selector (test2) object:nil];</p></p><p align="left"><p align="left">Creating objects, encapsulating Operations</p></p><p align="left"><p align="left">Nsblockoperation *operation3=[nsblockoperation blockoperationwithblock:^{</p></p><p align="left"><p align="left">NSLog (@ "nsblockoperation3--1----%@", [nsthread currentthread]);</p></p><p align="left"><p align="left">}];</p></p><p align="left"><p align="left">[operation3 addexecutionblock:^{</p></p><p align="left"><p align="left">NSLog (@ "nsblockoperation3--2----%@", [nsthread currentthread]);</p></p><p align="left"><p align="left">}];</p></p><p align="left"><p align="left"></p></p><p align="left"><p align="left">Create Nsoperationqueue</p></p><p align="left"><p align="left">Nsoperationqueue * Queue=[[nsoperationqueue alloc]init];</p></p><p align="left"><p align="left">Add an action to a queue</p></p><p align="left"><p align="left">[queue addoperation:operation1];</p></p><p align="left"><p align="left">[queue addoperation:operation2];</p></p><p align="left"><p align="left">[queue addoperation:operation3];</p></p><p align="left"><p align="left"></p></p><p align="left"><p align="left">}</p></p><p align="left"><p align="left"></p></p><p align="left"><p align="left">-(void) test1</p></p><p align="left"><p align="left">{</p></p><p align="left"><p align="left">NSLog (@ "nsinvocationoperation--test1--%@", [nsthread currentthread]);</p></p><p align="left"><p align="left">}</p></p><p align="left"><p align="left">-(void) test2</p></p><p align="left"><p align="left">{</p></p><p align="left"><p align="left">NSLog (@ "nsinvocationoperation--test2--%@", [nsthread currentthread]);</p></p><p align="left"><p align="left">}</p></p><p align="left"><p align="left">Print results</p></p><p align="left"><p align="left"></p></p><p><p>Attention</p></p><p><p>The system automatically takes out the Nsoperation object in the Nsoperationqueue and puts its encapsulated operation into a new thread to Execute. In the above code example, there are four tasks, Operation1 and Operation2 have one task, and Operation3 has two tasks. Altogether four tasks, four threads were opened. The time to execute the task is all 302, as you can see, these tasks are executed in Parallel.</p></p><p><p>Tips:</p></p><p><p>The queue is taken out in sequence and is not contradictory to the printed Result. The result is not necessarily who successively</p></p><p><p></p></p><p><p>I. Introduction of GCD</p></p><p><p>1. GCD full name Grand Central Dispatch can be translated as "the backbone dispatcher"</p></p><p><p>2, the advantages of GCD</p></p><p><p>GCD is Apple's solution for multi-core parallel computing</p></p><p><p>GCD will automatically take advantage of more CPU cores (such as dual-core, quad-core)</p></p><p><p>GCD automatically manages the life cycle of threads (create threads, schedule tasks, Destroy Threads)</p></p><p><p>Programmers just need to tell gcd what tasks they want to perform, without having to write any thread management code</p></p><p><p>3. Tips</p></p><p><p>(1) GCD exists in libdispatch.dylib this library, this library contains all the gcd, but any iOS program, the default load of the library, in the process of running the program will dynamically load the library, do not need to manually import.</p></p><p><p>(2) GCD is a pure C language, so when we write GCD related code, we face the function, not the Method.</p></p><p><p>(3) most of the functions in GCD start with dispatch</p></p><p><p>Ii. Tasks and queues</p></p><p><p>There are two core concepts in GCD</p></p><p><p>(1) Task: what action to perform</p></p><p><p>(2) queue: for storing tasks</p></p><p><p>The use of GCD is a two-step process</p></p><p><p>(1) Custom Tasks</p></p><p><p>(2) determine what you want to do</p></p><p><p>Adding tasks to the queue, gcd automatically takes the tasks from the queue and puts them in the corresponding thread</p></p><p><p>Tip: the removal of a task follows the FIFO principle of the queue: first-in, last-out</p></p><p><p>III. implementation of the mandate</p></p><p><p>1. Type of queue</p></p><p><p>The GCD queue can be divided into two major types</p></p><p><p>(1) concurrent queues (Concurrent Dispatch Queue)</p></p><p><p>Multiple tasks can be executed concurrently (simultaneously) (automatically opening multiple threads simultaneously) concurrency features are only valid under asynchronous (dispatch_async) functions</p></p><p><p></p></p><p><p>(2) serial queuing (Serial Dispatch Queue)</p></p><p><p>Let the task execute one after the other (once a task has finished executing the next task)</p></p><p><p></p></p><p><p>Attention</p></p><p><p>There are 4 terms that are more easily confused: synchronous, asynchronous, concurrent, serial</p></p><p><p>Synchronous and asynchronous determine whether to open a new thread</p></p><p><p>Synchronous: performs a task in the current thread and does not have the ability to turn on new threads</p></p><p><p>Async: perform a task in a new thread with the ability to open a new thread</p></p><p><p>Concurrency and serialization determine how tasks are executed</p></p><p><p>Concurrency: multiple tasks concurrently (concurrently) executed</p></p><p><p>Serial: after a task is executed, the next task is executed</p></p><p><p>2, Serial to the column</p></p><p><p></p></p><p><p>There are two ways to get serial in GCD</p></p><p><p>(1) creating a serial queue using the Dispatch_queue_create function</p></p><p align="left"><p align="left">dispatch_queue_t dispatch_queue_create (const Char *label, dispatch_queue_attr_t attr); Queue name, Queue property, general null</p></p><p align="left"><p align="left">Example:</p></p><p align="left"><p align="left">dispatch_queue_t queue = Dispatch_queue_create ("wendingding", NULL); Create</p></p><p><p>Dispatch_release (queue); Non-arc needs to release manually created queues</p></p><p><p>(2) using the primary queue (the queue associated with the mainline Threads)</p></p><p><p>The primary queue is a special serial queue that comes with the gcd, and the tasks placed in the master queue are placed in the main thread to execute</p></p><p align="left"><p align="left">Use Dispatch_get_main_queue () to get the home row</p></p><p align="left"><p align="left">Example:</p></p><p><p>dispatch_queue_t queue = Dispatch_get_main_queue ();</p></p><p><p>2. Concurrent queues</p></p><p align="left"><p align="left">The GCD default already provides a global concurrency queue for the entire app to use, without the need to manually create</p></p><p align="left"><p align="left">Using the Dispatch_get_global_queue function to obtain a global concurrency queue</p></p><p align="left"><p align="left">dispatch_queue_t dispatch_get_global_queue (dispatch_queue_priority_t priority,unsigned Long flags); This parameter is temporarily useless and can be used with 0</p></p><p align="left"><p align="left">Example:</p></p><p align="left"><p align="left">This parameter is reserved for later use, temporarily not used, pass a 0.</p></p><p align="left"><p align="left">The first parameter is the priority, where the default is Selected. Gets a global default priority for concurrent Queues.</p></p><p><p>dispatch_queue_t queue = Dispatch_get_global_queue (dispatch_queue_priority_default, 0); Get global concurrency Queue</p></p><p><p></p></p><p align="left"><p align="left">Description: priority for global concurrent queues</p></p><p align="left"><p align="left">#define Dispatch_queue_priority_high 2//high</p></p><p align="left"><p align="left">#define Dispatch_queue_priority_default 0//default (medium)</p></p><p align="left"><p align="left">#define Dispatch_queue_priority_low (-2)//low</p></p><p><p>#define Dispatch_queue_priority_background Int16_min//backstage</p></p><p><p>Execution effects for various queues</p></p><p><p></p></p><p><p></p></p><p><p>iOS multi-threaded learning and summary</p></p></span>
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