iOS 如何保持線程一直在運轉

來源:互聯網
上載者:User

標籤:休眠   oba   hang   use   sel   als   nil   條件   led   

1、簡單的可以想到,寫一個while迴圈

    while (TRUE) {            }

  但是這種方式存在缺陷,將導致CPU佔用100%,兩個核。

 

這種方式不優雅,會導致迴圈空轉,佔用大量CPU。即使在迴圈中加入sleep也不是特別好的方式。

 

2、在iOS中特有的方式,使用Runloop是否結束作為迴圈判斷條件

  

    [NSTimer scheduledTimerWithTimeInterval:[[NSDate distantFuture] timeIntervalSinceNow]                                     target:self                                   selector:@selector(ignore:)                                   userInfo:nil                                    repeats:YES];        NSThread *currentThread = [NSThread currentThread];    NSRunLoop *currentRunLoop = [NSRunLoop currentRunLoop];        BOOL isCancelled = [currentThread isCancelled];        NSLog(@"hello 1");    while (!isCancelled && [currentRunLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]])    {        NSLog(@"hello 2");        isCancelled = [currentThread isCancelled];    }    NSLog(@"hello 3");

  在建立的線程體中運行上面的代碼,將輸出:

2017-03-22 19:28:50.693824 NSThreadTest[3459:785928] hello 1

  這個時候線程像是阻塞在while處,而是處於休眠狀態,當Runloop中有事件來源的時候,線程會喚醒,並且執行處理對應事件的方法。

  看起來相當神奇!當線程結束的時候,會輸出hello 3,此時的CPU佔用如下

  

 

 

  除了以上實現方式之外,還有更優雅的實現:

 /*    //佔用0%的CPU    BOOL shouldKeepRunning = YES;        // global    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];    [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode]; // adding some input source, that is required for runLoop to runing    while (shouldKeepRunning && [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]); // starting infinite loop which can be stopped by changing the shouldKeepRunning‘s value    */        /*    //佔用0%的CPU    @autoreleasepool {        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];        [runLoop addPort:[NSMachPort port] forMode:NSRunLoopCommonModes];        [runLoop run];    }     */

  

3、總結

  iOS中的NSThread是對unix 中 pthread的一種封裝,並加入了Runloop的概念,以這種事件驅動線程的方式最佳化整體效能,也方便線程的調度使用。

4、原始碼

  https://github.com/liqiushui/NSThreadKeepAlive.git 

 

iOS 如何保持線程一直在運轉

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.