iOS Learning note 11-getting started with multithreading

Source: Internet
Author: User
<span id="Label3"></p>one, iOS multi-threaded iOS multi-threaded development has three kinds of ways: <ol> <ol> <li>Nsthread</li> <li>Nsoperation</li> <li>GCD</li> </ol> </ol><p><p>iOS creates a <strong>main</strong> thread after each process is started, <code>更新UI要在主线程上</code> so also known as the <strong>UI thread</strong> , which is the parent thread of other THREADS.</p></p>The difference between threads and processes is not clear: <ul> <ul> <li>Thread: used to refer to code snippets that are executed independently.</li> <li>Process: used to refer to a running executable program that can contain multiple threads.</li> </ul> </ul><p><p></p></p>second, Nsthread<p><p>Nsthreadhi Lightweight multithreaded development, you need to manage the thread life cycle yourself</p></p>To create a thread main implementation method:<pre class="objc"><pre class="objc"><code class="hljs objectivec"><span class="hljs-comment">/* 直接将操作添加到新线程中并执行,该方法无法拿到线程对象 */+ (<span class="hljs-keyword">void)detachNewThreadSelector:(SEL)selector <span class="hljs-comment">/* 方法名 */ toTarget:(<span class="hljs-keyword">id)target <span class="hljs-comment">/* 调用对象 */ withObject:(<span class="hljs-keyword">id)argument; <span class="hljs-comment">/* 参数 */<span class="hljs-comment">/* 创建线程对象,初始化线程任务,调用start方法启动线程 */- (instancetype)initWithTarget:(<span class="hljs-keyword">id)target <span class="hljs-comment">/* 调用对象 */ selector:(SEL)selector <span class="hljs-comment">/* 方法名 */ object:(<span class="hljs-keyword">id)argument;<span class="hljs-comment">/* 参数 */</span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre></pre>Actual use:<pre class="objc"><pre class="objc"><code class="hljs objectivec"><span class="hljs-comment">/* 创建一个线程,初始化任务,创建线程并不会启动线程 */<span class="hljs-built_in">NSThread *thread = [[<span class="hljs-built_in">NSThread alloc] initWithTarget:<span class="hljs-keyword">self selector:<span class="hljs-keyword">@selector(loadImage) object:<span class="hljs-literal">nil];[thread start];<span class="hljs-comment">//启动线程<span class="hljs-comment">/* 直接将操作添加到新线程并启动线程 */[<span class="hljs-built_in">NSThread detachNewThreadSelector:<span class="hljs-keyword">@selector(loadImage) toTarget:<span class="hljs-keyword">self withObject:<span class="hljs-literal">nil];</span></span></span></span></span></span></span></span></span></span></span></span></code></pre></pre> <blockquote> <blockquote> <ul> <li>The actual order of execution for each thread does not necessarily follow the boot order</li> </ul> </blockquote> </blockquote> <ul> <ul> <li>If it is a single-core cpu, multithreading is concurrency, split time slices to perform different threads, multi-core CPU multithreading is the real parallel operation.</li> </ul> </ul>The thread state is divided into: <ul> <ul> <li>Isexecuting (executing)</li> <li>isfinished (already Completed)</li> <li>iscancellled (has been Canceled)</li> </ul> </ul>The following are common ways to control threads:<pre class="objc"><pre class="objc"><code class="hljs objectivec"><span class="hljs-comment">/* 让线程休眠 */+ (<span class="hljs-keyword">void)sleepUntilDate:(<span class="hljs-built_in">NSDate *)date;<span class="hljs-comment">/* 让当前执行线程休眠到某个时间 */+ (<span class="hljs-keyword">void)sleepForTimeInterval:(<span class="hljs-built_in">NSTimeInterval)time;<span class="hljs-comment">/* 让当前执行线程休眠固定多少秒 */<span class="hljs-comment">/* 终止线程 */+ (<span class="hljs-keyword">void)exit;<span class="hljs-comment">/* 停止线程,注意在主线程中调用仅仅只是设置线程状态,不会立刻停止线程 */- (<span class="hljs-keyword">void)cancel;</span></span></span></span></span></span></span></span></span></span></span></code></pre></pre>Instance:<pre class="objc"><pre class="objc"><code class="hljs objectivec"><span class="hljs-built_in">NSThread *thread = threads[i];<span class="hljs-comment">//判断线程是否完成,如果没有完成则设置为取消状态<span class="hljs-comment">//注意设置为取消状态仅仅是改变了线程状态而言,并不能立刻终止线程<span class="hljs-keyword">if ( !thread.isFinished ) { [thread cancel];}<span class="hljs-comment">//线程休眠2秒[<span class="hljs-built_in">NSThread sleepForTimeInterval:<span class="hljs-number">2.0];</span></span></span></span></span></span></span></code></pre></pre><p><p>We know how to control a single thread, how to communicate between threads?</p></p>The following are common ways to communicate between threads:<pre class="objc"><pre class="objc"><code class="hljs objectivec"><span class="hljs-comment">/* 在后台执行一个操作,本质就是重新创建一个线程执行当前方法 */- (<span class="hljs-keyword">void)performSelectorInBackground:(SEL)aSelector withObject:(<span class="hljs-keyword">id)arg;<span class="hljs-comment">/* 在指定的线程上执行一个方法,需要用户创建一个线程对象 */- (<span class="hljs-keyword">void)performSelector:(SEL)aSelector onThread:(<span class="hljs-built_in">NSThread *)thr withObject:(<span class="hljs-keyword">id)arg waitUntilDone:(<span class="hljs-built_in">BOOL)wait;<span class="hljs-comment">/* 在主线程上执行一个方法 */- (<span class="hljs-keyword">void)performSelectorOnMainThread:(SEL)aSelector withObject:(<span class="hljs-keyword">id)arg waitUntilDone:(<span class="hljs-built_in">BOOL)wait;</span></span></span></span></span></span></span></span></span></span></span></span></code></pre></pre>third, nsoperation<p><p>Execution is initiated as soon as the nsoperation is placed in the Nsoperationqueue thread Queue.<br>Nsoperationqueue is responsible for managing and executing all nsoperation, which makes it easier to <strong>manage the total number of threads</strong> and to <strong>control dependencies between threads</strong> .</p></p>Nsoperation is a base class, and we are using its subclasses directly: <ul> <ul> <li>Nsinvocationoperation: the way that the method sel is invoked can be used by the thread of execution</li> <li>Nsblockoperation: the way that the execution thread calls block can use it</li> </ul> </ul>Here is the usage example:<pre class="objc"><code class="hljs objectivec"><span class="hljs-comment">Creating Invocation Threads<span class="hljs-built_in">Nsinvocationoperation *invocationoperation = [[<span class="hljs-built_in">Nsinvocationoperation alloc] initwithtarget:<span class="hljs-keyword">Self selector:<span class="hljs-keyword">@selector (loadimage) object:<span class="hljs-literal">nil];<span class="hljs-comment">Note If you call the Start method directly, This operation will be called in the main thread<span class="hljs-comment"><span class="hljs-comment">//[invocationoperation start];//generally does not do so, but is added to the Nsoperationqueue <span class="hljs-comment">//create thread queue <span class="hljs-built_in">nsoperationqueue *operationqueue = [[<span class="]" hljs-built_in ">nsoperationqueue alloc] Init];operationqueue.maxconcurrentoperationcount = <span class="hljs-number">5; <span class="hljs-comment">//set Maximum number of concurrent threads <span class="hljs-comment">//note after adding to the thread queue, the threads in the queue begin to execute [operationqueue addoperation:invocationoperation]; <span class="hljs-comment">//create block thread <span class="hljs-built_in">nsblockoperation *blockoperation = [<span class="hljs-built_in">nsblockoperation blockoperationwithblock:^{[<span class="hljs-keyword">self LoadImage:[<span class="hljs-built_in">nsnumber numberwithint:<span class="hljs-number">0]];}]; <span class="hljs-comment">//added into thread queue [operationqueue addoperation:blockoperation]; </span> </span> </span> </span> </span> </span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre><p><p>If you find it troublesome to add nsblockoperation threading, There is an easy way to do this, and that is the Nsoperationqueue object method:</p></p><pre class="objc"><pre class="objc"><code class="hljs objectivec"><span class="hljs-comment">// 快捷添加NSBlockOperation[operationQueue addOperationWithBlock:^{ [<span class="hljs-keyword">self loadImage:[<span class="hljs-built_in">NSNumber numberWithInt:<span class="hljs-number">0]];}];</span></span></span></span></code></pre></pre><p><p>I said nsoperationqueue can control dependencies between threads, what's the matter? Imagine a scene, loading multiple pictures, But I think the last picture must be loaded first, the other picture loading premise is the last picture to be loaded, this time you can use the Dependency. Very simple.</p></p>Multiple picture loading examples:<pre class="objc"><code class="hljs objectivec">- (<span class="hljs-keyword">Void) loadimagewithmultithread{<span class="hljs-keyword">int count = row_count*column_count;<span class="hljs-comment">Create thread queue<span class="hljs-built_in">Nsoperationqueue *operationqueue = [[<span class="hljs-built_in">Nsoperationqueue alloc]init]; Operationqueue.maxconcurrentoperationcount =<span class="hljs-number">5;<span class="hljs-comment">Set maximum number of concurrent threads<span class="hljs-comment">Create a thread that loads the last picture<span class="hljs-built_in">Nsblockoperation *lastblockoperation = [<span class="hljs-built_in">Nsblockoperation blockoperationwithblock:^{[ <span class="hljs-keyword">self <span class="hljs-keyword">loadimage:[<span class="hljs-built_in">nsnumber numberwithint: (count<span class="hljs-number">-1)];}]; <span class="hljs-comment">//create multiple threads to download other pictures for <span class="hljs-keyword">(<span class="hljs-keyword">int i=<span class="hljs-number">0; i<count<span class="hljs-number">-1; ++i) { <span class="hljs-comment">//create multithreaded operations <span class="hljs-built_in">Nsblockoperation * Blockoperation = [<span class="hljs-built_in">nsblockoperation blockoperationwithblock:^{[self<span class="hljs-keyword">loadimage:[<span class="hljs-built_in">nsnumber numberWithInt : i]]; }]; <span class="hljs-comment">//set dependent action for the last picture loading operation, only the last picture is loaded and the other images begin to load [blockoperation adddependency:lastblockoperation]; [operationqueue addoperation:blockoperation]; } <span class="hljs-comment">//add the last Picture's load thread to the thread queue [operationqueue addoperation:lastblockoperation];}</span> </span> </span> </span> </span> </span> </span> </span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></span></code></pre><p><p></p></p>Iv. GCD<p><p>GCD also has a queue similar to nsoperationqueue, GCD Unified management of the tasks in the entire queue, GCD is the framework under the C Language.</p></p>Queues in GCD are divided into parallel queues and serial queues: <ul> <ul> <li>Serial Queue (serial): There is only one thread, and the actions added to the queue are executed sequentially in order of Addition.</li> <li>Concurrent queue (concurrent): There are multiple threads, and it will schedule these queues on the available processors, while ensuring that advanced tasks are prioritized, but not sequential.</li> </ul> </ul><p><p>In fact, there is a special queue in GCD that is the home <strong>row</strong> , which is used to perform the operation tasks on the main thread.</p></p>GCD execution methods are also divided into asynchronous execution and synchronous execution: <ul> <ul> <li>Dispatch_async (asynchronous execution): Appends a task directly to the queue, regardless of whether the task in the queue is finished or not done</li> <li>Dispatch_sync (synchronous execution): When a task in the queue finishes executing, the task is appended to the queue</li> </ul> </ul>Creation of serial queues and concurrent queues:<pre class="objc"><pre class="objc"><code class="hljs objectivec"><span class="hljs-comment">/*创建一个队列 第一个参数:队列名称 第二个参数:队列类型,DISPATCH_QUEUE_SERIAL串行,DISPATCH_QUEUE_CONCURRENT并发 注意:GCD的queue不是指针类型*/<span class="hljs-built_in">dispatch_queue_t serialQueue = dispatch_queue_create(<span class="hljs-string">"queue1", DISPATCH_QUEUE_SERIAL);<span class="hljs-built_in">dispatch_queue_t concurrentQueue = dispatch_queue_create(<span class="hljs-string">"queue2", DISPATCH_QUEUE_CONCURRENT);<span class="hljs-comment">/* 使用dispatch_get_global_queue() 方法取得一个全局的并发队列 */<span class="hljs-built_in">dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, <span class="hljs-number">0);</span></span></span></span></span></span></span></span></code></pre></pre>Asynchronous execution and synchronous execution of Queues:<pre class="objc"><pre class="objc"><code class="hljs objectivec"><span class="hljs-comment">//异步执行队列任务,第一个参数是队列,第二个参数是任务Block<span class="hljs-built_in">dispatch_async(queue, ^{ [<span class="hljs-keyword">self loadImage:[<span class="hljs-built_in">NSNumber numberWithInt:i]];}); <span class="hljs-comment">//同步执行队列任务,第一个参数是队列,第二个参数是任务Block<span class="hljs-built_in">dispatch_sync(queue, ^{ [<span class="hljs-keyword">self loadImage:[<span class="hljs-built_in">NSNumber numberWithInt:i]];}); </span></span></span></span></span></span></span></span></code></pre></pre> <ul> <ul> <li>In gdc, whether an operation is multithreaded or single-threaded, depends on the current queue type and execution method, only the queue type is a <strong>parallel queue and executes with asynchronous methods</strong> to execute <strong>concurrently in multiple threads</strong> .</li> <li><strong>serial</strong> queues can be <strong>executed sequentially</strong> , and asynchronous methods of parallel queues cannot determine the order of Execution.</li> <li><strong>updating the UI interface</strong> is best done with <strong>synchronous methods</strong> , and other operations using asynchronous METHODS.</li> </ul> </ul>Other task execution methods for gcd:<pre class="objc"><pre class="objc"><code class="hljs objectivec"><span class="hljs-comment">/* 重复执行某个任务,为了不阻塞线程可以使用dispatch_async()包装一下再执行 */dispatch_apply(size_t iterations, <span class="hljs-built_in">dispatch_queue_t queue, <span class="hljs-keyword">void (^block)(size_t));<span class="hljs-comment">/* 单次执行一个任务,此方法中的任务只会执行一次,重复调用也没办法重复执行(单例模式中常用此方法)*/<span class="hljs-built_in">dispatch_once(<span class="hljs-built_in">dispatch_once_t *predicate, dispatch_block_t block);<span class="hljs-comment">/* 常用:延迟delayInSeconds秒后在队列queue执行block操作 */dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * <span class="hljs-built_in">NSEC_PER_SEC)), <span class="hljs-built_in">dispatch_queue_t queue, dispatch_block_t block);</span></span></span></span></span></span></span></span></span></code></pre></pre>five, thread Synchronization<p><p>Why do I need thread synchronization? Because you want to solve the problem of multi-threaded resource looting</p></p>1.NSLock Sync Lock<pre class="objc"><pre class="objc"><code class="hljs objectivec"><span class="hljs-comment">//初始化锁对象<span class="hljs-built_in">NSLock *myLock = [[<span class="hljs-built_in">NSLock alloc] init];<span class="hljs-comment">//加锁[myLock lock];<span class="hljs-comment">//加锁后,下面的代码只能有一个线程进入执行<span class="hljs-keyword">if (_imageNames.count > <span class="hljs-number">0) { name = [_imageNames lastObject]; [_imageNames removeObject:name];}<span class="hljs-comment">//使用完解锁[myLock unlock];</span></span></span></span></span></span></span></span></code></pre></pre>[email protected] code block<pre class="objc"><pre class="objc"><code class="hljs objectivec"><span class="hljs-comment">//线程同步<span class="hljs-keyword">@synchronized(<span class="hljs-keyword">self){ <span class="hljs-keyword">if (_imageNames.count > <span class="hljs-number">0) { name = [_imageNames lastObject]; [_imageNames removeObject:name]; }}</span></span></span></span></span></code></pre></pre><p><p>Thread synchronization is not a small story, this is a chunk of knowledge.</p></p><p><p>iOS Learning note 11-getting started with multithreading</p></p></span>

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.