<span id="Label3"></p><em class="corner"><em class="corner">Summary</em></em>This article mainly introduces three kinds of multithreading techniques in iOS development: nsthread, nsoperation/nsoperationqueue, GCD. and tips and tricks in multithreaded programming. multithreading Nsthread nsoperation/ Nsoperationqueue<span class="tag"><span class="tag">GCD</span></span><p><p></p></p><p><p><em id="AnchorContentToggle" class="corner" style="cursor: pointer;" title="点击收起目录">Catalogue [-]</em></p></p> <ul> <ul> <li class="osc_h1">Multi-threaded in iOS</li> <li class="osc_h2">Three multithreaded technical features of Ios:</li> <li class="osc_h2">GCD Basic Ideas</li> <li class="osc_h3">Queue:</li> <li class="osc_h3">Operation:</li> <li class="osc_h3">Results of nested synchronization operations Dispatch_sync in different queues:</li> <li class="osc_h3">Application scenarios for synchronous operation Dispatch_sync:</li> <li class="osc_h3">GCD advantages:</li> <li class="osc_h3">GCD queue:</li> <li class="osc_h2">Nsoperation&nsoperationqueue</li> <li class="osc_h3">Brief introduction:</li> <li class="osc_h3">Queues and Operations:</li> <li class="osc_h3">Nsinvocationoperation (dispatch Operation)</li> <li class="osc_h3">Nsblockoperation (block Operation)</li> <li class="osc_h3">Nsoperation summary:</li> <li class="osc_h2">Multithreading Methods of NSObject</li> </ul> </ul>Multi-threaded in iOS<p><p>The first thing to know is what is multi-threading, the difference between processes and THREADS.</p></p><p><p>Process:</p></p><p><p>The ongoing program is called the process, which is responsible for the memory allocation of the program running;</p></p><p><p>Each process has its own independent virtual memory space.</p></p><p><p>Threads: (maximum 1M of stack space for the main thread, up to 512K of stack space per Stripe)</p></p><p><p>A thread is a separate execution path (control unit) in a process;</p></p><p><p>At least one thread is included in a process, that is, the main path;</p></p><p><p>Time-consuming execution paths (such as network requests) can be executed in other threads;</p></p><p><p>The thread cannot be killed, but it can pause/hibernate a thread.</p></p><p><p>Purpose of creating threads:</p></p><p><p>Opens a new execution path, runs the specified code, and runs concurrently with the code implementation in the main THREAD.</p></p><p><p>Multi-task Scheduling system:</p></p><p><p>Each application is allocated by the operating system for a short time slice (timeslice) in turn using the cpu, because the CPU to each time slice processing speed very quickly, therefore, The user appears that these tasks seem to be executed simultaneously.</p></p><p><p>Concurrent:</p></p><p><p>Refers to two or more tasks occurring at the same time interval, but at any point in time, the CPU will only process one Task.</p></p><p><p>Advantages of Multithreading:</p></p><p><p>1> takes full advantage of multi-core processor, assigning different thread tasks to different processors and really entering the "parallel operation" state;</p></p><p><p>2> allocates time-consuming tasks to other threads, and the unified update interface from the main thread will make the application smoother and the user experience better;</p></p><p><p>3> when the number of hardware processors increases, The program runs faster, and the program does not need to make any adjustments.</p></p><p><p>Disadvantages:</p></p><p><p>New threads consume memory space and CPU time, and too many threads can degrade the performance of the System.</p></p>Three multithreaded technical features of Ios:<p><p>1.NSThread:</p></p><p><p>1> using Nsthread object to build a thread is very convenient;</p></p><p><p>2> but! It is very difficult to manage multiple threads using nsthread, not recommended;</p></p><p><p>3> tips! use [nsthread currentthread] to track task threads for these three technologies.</p></p><p><p><span style="font-size: 12.5px;">2.nsoperation/nsoperationqueue:</span></p></p><p><p><span style="font-size: 12.5px;">1> is a set of OBJECTIVE-C APIs implemented using gcd;<br></span></p></p><p><p><span style="font-size: 12.5px;">2> is an object-oriented multithreading technology;<br></span></p></p><p><p><span style="font-size: 12.5px;">3> provides some features that are not easily implemented in gcd, such as limiting the maximum number of concurrent quantities and the dependencies between operations.<br></span></p></p><p><p><span style="font-size: 12.5px;">3.GCD---Grand Central Dispatch:</span></p></p><p><p><span style="font-size: 12.5px;">1> is the underlying API based on C language;<br></span></p></p><p><p><span style="font-size: 12.5px;">2> defines the task with block, which is very flexible and convenient to Use.<br></span></p></p><p><p><span style="font-size: 12.5px;">The 3> provides more control and the underlying functions that are not available in the Operation Queue.<br></span></p></p><p><p><span style="font-size: 12.5px;">iOS developers need to be aware of the basic use of three multithreaded technologies, as the actual development will be based on the actual choice of different multithreading Techniques.<br></span></p></p>GCD Basic Ideas<p><p>The basic idea of GCD is to put the operation s in the queue s to Execute.</p></p><p><p>1> operation using blocks definition;</p></p><p><p>The 2> queue is responsible for scheduling the thread on which the task executes and the specific execution time;</p></p><p><p>The 3> queue is characterized by first in, out (FIFO), and new additions to the queue are queued at the end of the Team.</p></p><p><p>Tips:</p></p><p><p>The functions of GCD are all beginning with the dispatch (dispatch/dispatch).</p></p>Queue:<p><p>dispatch_queue_t</p></p><p><p>Serial Queue: the tasks in the queue are only executed sequentially;</p></p><p><p>Parallel queues: tasks in a queue are typically executed concurrently.</p></p>Operation:<p><p>Dispatch_async asynchronous operation, will be executed concurrently, unable to determine the order of execution of the task;</p></p><p><p>Dispatch_sync synchronization operations, which are executed sequentially, can determine the order in which the tasks are Executed.</p></p><p><p><span style="font-size: 12.5px;">The queue is not a thread and does not represent the corresponding CPU. the queue is responsible for scheduling. the purpose of multithreading is to achieve fast switching on one cpu!</span></p></p><p><p>In the serial queue:</p></p><p><p>Synchronous operation does not create new thread, operation order execution (useless!);</p></p><p><p>Asynchronous operations Create new threads, which are executed in sequence (very useful!) (scenario: an action that does not affect the main thread and is executed sequentially).</p></p><p><p>In a parallel queue:</p></p><p><p>The synchronization operation does not create new threads, and the operation sequence executes;</p></p><p><p>Asynchronous operations Create multiple threads, perform out-of-order execution (useful, error-prone), and, If there are other tasks before the queue, wait for the previous task to complete before executing. scenario: does not affect the main thread, do not need to perform the operation Sequentially.</p></p><p><p>Global Queue:</p></p><p><p>The global queue is a system, which can be used directly (get), similar to parallel, but cannot confirm the queue in which the operation is being Debugged.</p></p><p><p>Main Queue:</p></p><p><p>Each application corresponds to a single home row, direct get, and in multithreaded development, the UI is updated with the master queue;</p></p><p><p>Attention:</p></p><p><p><span style="font-size: 12.5px;">Operations in the master queue should be executed sequentially on the main thread, with no concept of asynchrony.</span></p></p><p><p><span style="font-size: 12.5px;">If the operation in the main thread is considered a large block, it will never end unless the main thread is killed by the User. therefore, the synchronization operation added in the master queue is never executed and will Deadlock.<br></span></p></p><span style="font-size: 18px;"><span style="font-size: 18px;">results of nested synchronization operations Dispatch_sync in different queues:</span></span>? <table border="0" cellspacing="0" cellpadding="0"> <tbody> <tr> <td class="gutter">12345678 </td> <td class="code"><code class="cpp comments">// Global queue, All executed on the main thread, Does not deadlock </code> <code class="cpp plain">dispatch_queue_t q = dispatch_get_global_queue (dispatch_ queue_priority_default, 0); </code> <code class="cpp comments">// parallel queue, both executed on the main thread and not deadlocked </code> <code class="cpp plain">dispatch_queue_t q = dispatch_queue_create (</code> <code class="cpp string" "m.baidu.com" < code> <code class="cpp plain">, dispatch_queue_concurrent); </code> <code class="cpp comments">// serial queue, deadlock, But the code before the nested synchronization operation is executed </code> <code class="cpp plain">dispatch_queue_t q = dispatch_queue_create (</code> <code class="cpp string" "m.baidu.com" < code> <code class="cpp plain">, dispatch_queue_serial); </code> <code class="cpp comments">// Direct Deadlock </code> <code class="cpp plain">dispatch_queue_t q = dispatch_get_main_queue (); </code> </code></code></td> </tr> </tbody> </table><span style="font-size: 12.5px;"><span style="font-size: 12.5px;"><span style="line-height: 23px;">application scenarios for synchronous operation Dispatch_sync:</span></span></span><p><p><span style="line-height: 23px;"><span style="font-size: 12.5px;">blocking the execution of a parallel queue requires that an operation be performed before subsequent operations, such as user Logons.</span></span></p></p><p><p><span style="font-size: 12.5px;">Make sure that the local variables outside the block code are actually modified.</span></p></p><p><p><span style="font-size: 12.5px;">[nsthread sleepfortimeinterval:2.0f] typically used in multithreaded debugging to simulate time-consuming operations, do not use this method in published applications!</span></p></p><p><p>Regardless of queue or task, the creation and recycling of threads does not require programmer involvement. the creation of a thread is handled by the Queue.</p></p>GCD advantages:<p><p>1> through gcd, developers no longer have to deal directly with threads, just add code blocks to the Queue.</p></p><p><p>2> GCD manages a thread pool at the back end, gcd not only determines which thread the code block will be executed on, but also manages the threads based on available system resources, freeing the developer from the work of thread management, and easing the problem of a large number of threads being created through a centralized management thread.</p></p><p><p>3> using gcd, developers can think of work as a queue rather than a bunch of threads, and this parallel abstraction model is easier to master and Use.</p></p>GCD queue:<p><p>Apple's official GCD queue:</p></p><p><p></p></p><p><p>As you can see<span style="font-size: 12.5px;"> , GCD exposes 5 different queues: the primary queue running in the main thread, 3 different priority background queues, and a lower-priority background queue for i/o.</span></p></p><p><p>Custom queues: serial and parallel Queues. custom queues are very powerful and are recommended for use in Development.</p></p><p><p>All blocks that are dispatched in the custom queue will eventually be placed in the System's global queue and thread Pool.</p></p><p><p>Tips:</p></p><p><p>It is not recommended to use a queue of different priorities, because if poorly designed, a priority reversal may occur, that is, low-priority operations block High-priority Operations.</p></p>Nsoperation&nsoperationqueue introduction:<p><p>1> Nsoperationqueue (operation Queue) is the cocoa abstraction of the queue model provided by gcd, and is a set of Objective-c apis;</p></p><p><p>The 2> GCD provides a lower level of control, while the Nsoperationqueue (operation Queue) implements some handy features on top of gcd, which are often the best and safest choice for developers.</p></p>Queues and Operations:<p><p>Nsoperationqueue has two different types of queues: the primary queue and the custom Queue.</p></p><p><p>The primary queue runs on the main thread, and the custom queue executes in the Background.</p></p><p><p>The tasks that the queue handles are subclasses of nsoperation: nsinvocationoperation and Nsblockoperation.</p></p><p><p>Nsoperation Basic steps to Use:</p></p><p><p>Define action queues--define actions and add actions to the Queue.</p></p><p><p>Tips:</p></p><p><p>Once the operation is added to the queue, the operation is scheduled to execute Immediately.</p></p>Nsinvocationoperation (dispatch Operation)<p><p>1> Define a Queue:</p></p>? <table border="0" cellspacing="0" cellpadding="0"> <tbody> <tr> <td class="gutter">1</td> <td class="code"><code class="cpp plain">self.myQueue = [[NSOpertaionQueue alloc] init];</code></td> </tr> </tbody> </table><p><p>2> Method of Operation Invocation:</p></p>? <table border="0" cellspacing="0" cellpadding="0"> <tbody> <tr> <td class="gutter">1234</td> <td class="code"><code class="cpp plain">-(</code><code class="cpp keyword bold">void</code><code class="cpp plain">)operationAction:(id)obj</code><code class="cpp plain">{</code><code class="cpp spaces"> </code><code class="cpp plain">NSLog(@</code><code class="cpp string">"%@----obj : %@ "</code><code class="cpp plain">,[NSThread currentThread], obj);</code><code class="cpp plain">};</code></td> </tr> </tbody> </table><p><p>3> define the operation and add it to the Queue:</p></p>? <table border="0" cellspacing="0" cellpadding="0"> <tbody> <tr> <td class="gutter">123</td> <td class="code"><code class="cpp plain">NSInvocationOperation *op = [[NSInvocationOperation alloc] </code><code class="cpp plain">initWithTarget:self selector:@selector(operationAction:) object:@(i)];</code><code class="cpp plain">[self.myQueue addOperation:op]</code></td> </tr> </tbody> </table><p><p>Tip: you need to prepare a scheduled method and be able to receive a parameter.</p></p>Nsblockoperation (block Operation)<p><p>Define the action and add to the Queue:</p></p>? <table border="0" cellspacing="0" cellpadding="0"> <tbody> <tr> <td class="gutter">1234</td> <td class="code"><code class="cpp plain">NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{</code><code class="cpp spaces"> </code><code class="cpp plain">[self operationAction:@</code><code class="cpp string">"Block Operation"</code><code class="cpp plain">];</code><code class="cpp plain">}];</code><code class="cpp plain">[self.myQueue addOperation:op];</code></td> </tr> </tbody> </table><p><p>Nsblockoperation is more flexible than nsinvocationoperation;</p></p><p><p>To set the dependencies for an operation:</p></p><p><p>You can use "adddependency" to specify dependencies (execution order) between operations, but be careful not to have circular dependencies.</p></p><p><p>To set the number of concurrent threads:</p></p>? <table border="0" cellspacing="0" cellpadding="0"> <tbody> <tr> <td class="gutter">1</td> <td class="code"><code class="cpp plain">[self.myQueue setMaxConcurrentOperationCount:2];</code></td> </tr> </tbody> </table>Nsoperation summary:<p><p>In essence, the performance of the operations queue is slightly lower than gcd, but in most cases this negative effect is negligible. the action queue is the preferred tool for concurrent programming.</p></p><p><p>here, recommend a very useful Third-party programming framework afn, the bottom with GCD development, the development of the interface is Nsoperation.</p></p><p><p>Circular reference problems in Multi-threading:</p></p><p><p>A circular reference can be caused if the Self object holds a reference to an operand, and the manipulation object directly accesses Self.</p></p><p><p>Using self in a manipulation object alone does not cause circular references.</p></p><p><p>Note: do not use [weakself] at this Time.</p></p><p><p>Resource sharing issues in Multi-threading:</p></p><p><p>Many of the problems in concurrent programming are rooted in the ability to access shared resources in multiple THREADS. A resource can be a property, an object, a network device, or a file.</p></p><p><p>Any shared resource in multiple threads can be a potential conflict point and must be carefully designed to prevent this conflict from Occurring.</p></p><p><p>To ensure performance, atomic only protects the setter method for Attributes.</p></p><p><p>When competing for shared resources, if the getter method of a property is involved, you can use a mutex (@synchronized) to ensure that the properties are safe to read and write between multiple threads.</p></p><p><p>Whether it is atomic or @synchronized, the cost of use is High.</p></p><p><p>Suggestions:</p></p><p><p>Multithreading is an efficient way to perform multiple tasks concurrently, and if possible, you should avoid competing for shared resources in the THREAD.</p></p><p><p>For performance reasons, The vast majority of classes in Uikit are not thread-safe, so Apple requires that updates to ui-related operations be performed in the main thread.</p></p>Multithreading Methods of NSObject<p><p>1> How to open a background task:</p></p>? <table border="0" cellspacing="0" cellpadding="0"> <tbody> <tr> <td class="gutter">1</td> <td class="code"><code class="cpp plain">- (</code><code class="cpp keyword bold">void</code><code class="cpp plain">)performSelectorInBackground:(SEL)@Selector withObject:(id)arg</code></td> </tr> </tbody> </table><p><p>2> notifies the main thread of the way to perform tasks in the background threads:</p></p>? <table border="0" cellspacing="0" cellpadding="0"> <tbody> <tr> <td class="gutter">1</td> <td class="code"><code class="cpp plain">- (</code><code class="cpp keyword bold">void</code><code class="cpp plain">)performSelectorOnMainThread:(SEL)@Selector withObject:(id)arg waitUntilDone:(</code><code class="cpp color1 bold">BOOL</code><code class="cpp plain">)wait</code></td> </tr> </tbody> </table><p><p>3> Getting thread information</p></p>? <table border="0" cellspacing="0" cellpadding="0"> <tbody> <tr> <td class="gutter">1</td> <td class="code"><code class="cpp plain">[NSThread currentThread]</code></td> </tr> </tbody> </table><p><p>4> thread hibernation</p></p>? <table border="0" cellspacing="0" cellpadding="0"> <tbody> <tr> <td class="gutter">1</td> <td class="code"><code class="cpp plain">[NSThread sleepForTimeInterval:2.0f];</code></td> </tr> </tbody> </table><p><p>Characteristics:</p></p><p><p>1> Use simple, lightweight;</p></p><p><p>2> cannot control the number of threads and the order in which they are executed.</p></p><p><p>NSObject Multithreading Method Considerations:</p></p><p><p>The multithreading method of the 1> NSObject uses the Nsthread multithreading Technique.</p></p><p><p>2> Nsthread's Multithreading technology does not automatically use @autoreleasepool.</p></p><p><p>When using NSObject or Nsthread multithreading techniques, if you are involved in object assignment, you need to add @autoreleasepool manually.</p></p><p><p>Multithreading in iOS development Note--ios</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.