What exactly is called "Run Loop" here?
Before continuing to read in the docs, my brain is stuck at this point:
- (void)threadMainRoutine {
BOOL moreWorkToDo = YES;
BOOL exitNow = NO;
NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; // is this THE run loop?
// some stuff...
while (moreWorkToDo && !exitNow) { // or is THIS the run loop?
// some stuff
[runLoop runUntilDate:[NSDate date]];
// some stuff
}
// some stuff
}
I've added some comments to the sample code. Maybe someone can explain this why there is a while loop if there is a runLoop object that receives the -runUntilDate: message. I mean: who is here? I see two. First, while this is clearly running the loop, then it calls a method that sounds like the loop works well.
stateConfused = YES;
pleaseExplain = YES;
Technically, the loops are NSRunLoop
internally (these are "to date" loops). This gives you a periodic opportunity to exit the stream - if you use run
instead runUntilDate:
then it NSRunLoop
will loop inside forever (you won't need to wrap it in a while loop, but you can never stop that either). This is normal behavior for the main thread and not for worker threads, which usually have exit conditions that require periodic checking.
runLoop
will never change the value moreWorkToDo
or exitNow
(you are responsible for this when the thread's work is done or the user left the application), but this is how you decide if you want the end to complete.
Depending on how you want your thread to behave, you can replace these flags with [NSApp isRunning]
and [tasksRemainingForThisThreadToProcess count] != 0
or similar.
(Race condition warning: if you end a thread when all other tasks are processed, be careful to never send another task to the thread when tasksRemainingForThisThreadToProcess
empty, as this indicates the thread will terminate.)
source to share
the first one is the actual runloop, the runloop returned [NSRunLoop currentRunLoop]
is created with UIApplication. Simplified, it receives all OS events (keyboard, mouse, etc.) and sends them to your program. If you choose [runLoop runUntilDate:[NSDate date]];
, this will return after the specified date has passed, but your program will continue to receive OS events. See Link.
This is different from calling:
[[NSThread currentThread] sleepFormTimeInterval:]
which will send your thread completely and it won't even receive OS events.
source to share