views:

38

answers:

1

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.

+2  A: 

[[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.
Graham Lee
My experience is that calling run will cause the NSThread to terminate if nothing has been put on the thread yet. Is the only way to keep it alive by putting a while loop around run with a condition?
Paul
If you need it to stay around, add a source.
Graham Lee
I've read about sources...Can you give me an example how to add a source?
Paul
There's info at the following link but it seems confusing...http://developer.apple.com/library/mac/documentation/cocoa/conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#//apple_ref/doc/uid/10000057i-CH16-SW7
Paul
actually listings 3-3 to 3-8 in that page do exactly what you need.
Graham Lee