ios 线程休眠_iOS 如何保持线程一直在运转

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值