简体   繁体   English

iOS中的空闲线程方法

[英]Idle thread approach in iOS

I'm trying to set up a thread that stays idle until new data it's available. 我正在尝试建立一个在新数据可用之前一直处于空闲状态的线程。 What it's the best approach for this in Objective-C? 在Objective-C中,最好的方法是什么? Till now I tried to make a simple run loop 到现在为止,我一直试图做一个简单的运行循环

while(YES) {
   if(isDataAvailable) {
      //process data
   }
}

However this has an huge impact on performance, my FPS drops from 40 to 20 and the interface becomes unusable (even if the actual data process happens once in a second or so and it's not very intense for the CPU. I tried to add [NSThread sleepForTimeInterval:0.01] at the end, but this way I lose data packages ('process data' refers to some streaming related operations, queue and unqueue data packages), however the FPS returns to normal. 但是,这对性能有很大的影响,我的FPS从40下降到20,并且接口变得不可用(即使实际的数据处理[NSThread sleepForTimeInterval:0.01]发生一次,并且对CPU来说也不是很[NSThread sleepForTimeInterval:0.01] 。我尝试添加[NSThread sleepForTimeInterval:0.01]最后, [NSThread sleepForTimeInterval:0.01] ,但是这样我丢失了数据包(“过程数据”指的是一些与流相关的操作,队列和非队列数据包),但是FPS恢复正常。

I'm fair new in Objective-C and I was thinking maybe there is a better way to do this? 我是Objective-C的新手,我在想也许有更好的方法可以做到这一点? I also had a look over NSRunLoop, but didn't manage to make it work as a run loop :), only attached a timer to it that doesn't do more than my [NSThread sleepForTimeInterval:0.01] thing. 我还查看了NSRunLoop,但没有设法使其像运行循环一样工作:),仅向其附加了一个计时器,该计时器的作用不超过我的[NSThread sleepForTimeInterval:0.01]

Any help it's highly appreciated:D 非常感谢您的任何帮助:D

If you need to keep the seconary thread alive, you definitely want to use a real runloop: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#//apple_ref/doc/uid/10000057i-CH16-SW1 如果需要使辅助线程保持活动状态,则肯定要使用真正的运行循环: http : //developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#// apple_ref / doc / uid / 10000057i-CH16-SW1

Basically, just create and start your thread, set up an autorelease pool, then run your runloop for some set time amount. 基本上,只需创建并启动线程,设置一个自动释放池,然后在一定的设置时间内运行runloop。 When the time expires, you check to see if you should exit your thread, or enter into the runloop again. 时间到时,您检查是否应该退出线程,还是再次进入运行循环。

As Marcelo points out though, there are more modern approaches to achieve concurrency (GCD and async dispatch being a couple of examples) so maybe investigate other forms of concurrency as well. 正如Marcelo指出的那样,有更多现代方法可以实现并发(GCD和异步分派是几个示例),因此也许也可以研究其他形式的并发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM