NSRunLoop issue
NSRunLoop issue
- Subject: NSRunLoop issue
- From: Andreas Grosam <email@hidden>
- Date: Thu, 17 Sep 2009 16:41:29 +0200
How can I prevent a run loop from returning immediately if there is no
input source and no timer attached ?
Following problem:
I use a separate thread where several periodic timers shall be
attached and detached to the thread's run loop. The timers shall be
attached and detached (read added and invalidated) across the life of
the application. The timers are the only things attached to the run
loop, that is, I don't explicitly add any other input sources. Setting
and removing the timers is initiated from the main thread - but
actually performed in the timer's thread by invoking
performSelector:onThread:withObject:waitUntilDone: from the main thread.
During the life of the application, or especially at the start, it
might happen, that there are no timers active - but timers may be
added later on.
Now, the docs state, that a run loop will exit "immediately" when
there is no timer and no input source. That is, it might happen that
the thread stops immediately after it started. That is, that it is not
even possible to have a chance to add a timer, via a method which is
actually performed on this thread because the thread did stop far too
quickly.
My first approach to prevent the thread to stop prematurely is
implementing the run method (which is invoked by the thread's main
method) like this:
- (void) run
{
BOOL processedInputSource;
while (!self.stopped) {
processedInputSource = [runLoop runMode:NSDefaultRunLoopMode
beforeDate:[NSDate distantFuture]]);
}
}
That is, the life of the thread will be controlled by an ivar namely
stopped. It is initially set to to NO, and only set to YES via a
method -stop that is scheduled in this thread via
performSelector:onThread:withObject:waitUntilDone:.
The good thing with this approach is, that it is quite easy to remove
and add timers and it is also very easy, to explicitly stop the thread
when it is required without facing synchronization issues. It works
perfectly as long there is a timer (or an input source), since the run
loop will block then and not causing a busy loop.
However, when there is no timer attached (and no other input source),
it causes a the run loop to not block, that is, returning quickly,
which in turn forces the CPU to do elaborately effectively nothing.
How can I prevent the busy loop, or achieve my goals with a better
design?
Thanks in advance for ideas.
Regards
Andreas
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden