开发者

Proper way to start/continue runloop

开发者 https://www.devze.com 2023-01-16 17:29 出处:网络
While I开发者_开发知识库 usually make use of NSOperation for having a thread do a short task/operation, I\'d like to have a long-living dedicated thread that is always available to process certain ope

While I开发者_开发知识库 usually make use of NSOperation for having a thread do a short task/operation, I'd like to have a long-living dedicated thread that is always available to process certain operations. For this, I allocate a new NSThread and use the initWithTarget method:

- (id)initWithTarget:(id)target selector:(SEL)selector  object:(id)argument

My understanding is the selector passed in should be the thread's main method that is responsible for starting the runloop. What is the proper code to have in there?

Is a while loop like this appropriate...

(void)newThreadMainMethod {
    while(1) {
      [[NSThread currentThread] run];
    }
}

or is there a more efficient way to do it so that the thread doesn't take up resources with a endless loop? I was thinking along the lines of having a timer wake up every 0.5 seconds and call run on the thread in case something new is available to work on. I would appreciate your input.

Thanks.


[[NSRunLoop currentRunLoop] run] is what you want, but it will carry on forever so you only need to call it once (not in a loop). You can either:

  • do that, terminating the thread from within the run loop when/if appropriate
  • use [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: JIFFY_TIME], and poll for an exit condition in a while() loop like you've written.
0

精彩评论

暂无评论...
验证码 换一张
取 消