views:

362

answers:

2

Hey guys! I'm messing around with threads a little bit. Now consider this: I have a main thread. I start a new thread. In it's entry-point method, I want to make a run loop. Now the documentation tells meh that I have to have a input source. Otherwise my run loop exits immediately. bad. okay. but I have no other input source than my performSelector... method calls. After the thread is started, there comes a performSelector method that will kick in another method on that thread after some delay. inside that method another performSelector call happens, and so on. each with a delay between 0.1 and 1 sec. So a repeatedly firing timer is senseless right ;-)

How could I set up that run loop so it keeps alive to receive kicks from performSelector? I want the thread to sleep when there's nothing to do. but when a performSelector kick is comming in his butt, I want that the thread wakes up and works.

Any suggestions, anyone?

A: 

You don't describe what you're REALLY trying to do, so it's difficult to tell, but it sounds like you're overcomplicating things a bit.

I believe that you want to have just one thread (kicked off in whatever way you like) and that thread should make use of NSCondition/NSLock to sleep until you want it to wake up.

See this S.O. thread for a similar question and a good answer explaining how to do it:

Olie
While you could implement the requested producer-consumer model this way, it would add a lot of extra code that is built into run loops. They already know how to respond to selectors, so we don't need to create extra condition objects to manage the messages.
Rob Napier
+2  A: 

The code you want is explained in Figure 3-14 in Run Loops in the Threading Programming Guide. But it's buried so well in other discussion that if you don't understand everything else on this page, you won't quite know what you're looking at. Read that section, and then this code will hopefully make sense:

- (void)startRunLoop:(id)sender
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // Any thread setup

    do
    {
     [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                                 beforeDate:[NSDate distantFuture]];
    } while (self.isStarted);

    // Any thread cleanup

    [pool release];
}
Rob Napier
Proviso: As per the doc you linked to, you first need to set up an input source or run loop event of some kind, otherwise the run loop will immediately exit, taking the thread to 100% CPU utilization while it waits for commands. The simplest way I know of doing this is with a dummy port: `[[NSRunLoop currentRunLoop] addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode]`
Benji XVI