保持NSThread活着,并运行NSRunLoop就可以了 [英] Keep NSThread alive and run NSRunLoop on it

查看:225
本文介绍了保持NSThread活着,并运行NSRunLoop就可以了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我开始一个新的NSThread,我想以后可以通过调用 performSelector:onThread:... 。从我如何理解它调用该方法添加该调用到该线程上的runloop,所以在下一次迭代它将弹出所有这些调用,并随后调用,直到没有什么可以调用。所以我需要这种功能,一个空闲线程准备工作,我只是可以调用它。我当前的代码如下所示:

So I'm starting a new NSThread that I want to be able to use later by calling performSelector:onThread:.... From how I understand it calling that methods add that call to the runloop on that thread, so on its next iteration it will pop all these calls and subsequently call them until there is nothing left to call. So I need this kind of functionality, an idle thread ready for work that I just can call upon it. My current code looks like this:

   - (void)doInitialize
   {
       mThread =  [[NSThread alloc] initWithTarget:self selector:@selector(runThread) object:nil];
       [mthread start];
   }

   - (void)runThread
   {
       NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init];

       // From what I understand from the Google machine is that this call should start the
       // runloop on this thread, but it DOESN'T. The thread dies and is un-callable
       [[NSRunLoop currentRunLoop] run];

       [pool drain];
   }

   - (void)scheduleSomethingOnThread
   {
       [self performSelector:@selector(hardWork) onThread:mThread withObject:nil waitUntilDone:NO];
   }

但线程不会保持活动,而performSelector:onThread不会任何东西。

But the thread is not kept alive, and the performSelector:onThread does not do anything. How do I go about this the right way?

推荐答案

运行循环需要至少一个输入源才能运行。主运行循环,但是你必须手动添加一个源来获得一个辅助运行循环的 -run 方法做任何事情。这里有一些文档这里

A run loop requires at least one "input source" to run. The main run loop does, but you have to add a source manually to get a secondary run loop's -run method to do anything. There's some documentation on this here.

一个简单的方法来让这个工作只是把 [[NSRunLoop currentRunLoop] 在无限循环中;当有事情要做,它会做到,否则立即返回。问题是线程将花费相当多的处理器时间,只是等待某事发生。

One naïve way to get this to work would be just to put [[NSRunLoop currentRunLoop] run] in an infinite loop; when there's something to do, it'll do it, and return immediately otherwise. The problem is that the thread will take a decent amount of processor time simply waiting for something to occur.

另一个解决方案是在这个运行循环上安装一个NSTimer alive。

Another solution is to install an NSTimer on this run loop to keep it alive.

但是,如果可能的话,你应该使用为这种事情设计的机制。如果可能,您可能需要使用 NSOperationQueue 进行后台操作。

But, if possible, you should use a mechanism designed for this sort of thing. If possible, you may want to use NSOperationQueue for background operations.

这篇关于保持NSThread活着,并运行NSRunLoop就可以了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆