N0un
N0un

Reputation: 868

Result of calling performSelector: on a "sleeping" thread's current run loop?

I asked myself a question, but have no answer yet so I hope you could have one:

What happened if there is a NSThread having his current NSRunLoop(named runLoop1 for example) in "sleeping" state (well, runLoop1 called [NSThread sleepForTimeInterval:/*...*/]) while an other NSThread is calling [self performSelector:@selector(selector:) onThread:runLoop1 withObject:nil waitUntilDone:NO]?

I hope I'm understandable ^^

Upvotes: 0

Views: 90

Answers (1)

Matic Oblak
Matic Oblak

Reputation: 16774

The runloop can be explained as an infinite loop:

while(!exit) {
   // Do stuff here
}

This runs on a thread and if this thread is in sleep then so is the loop and no events will be called on it.

So then what are performSelector methods:

Imagine there is an array of invocations with that loop which will be executed when appropriate. Since there is a method to perform the selector after a delay there is also a time stamp.

while(!exit) {
   NSMutableArray *notExecuted = [NSMutableArray new];
   for(Executable *item in [self.pendingExecutables copy]) {
      if(item.executionDate && [item.executionDate compare:[NSDate date]] == NSOrderedDescending) {
          [notExecuted addObject:item];
      } 
      else {
           [item execute];
      }
   }
   self.pendingExecutables = notExecuted;
}

So calling performSelector really does nothing but adds the data needed to perform it into some array. The runloop must be running for the execution to actually happen. So in your case nothing happens, the selector will not be performed because the loop is not executing since the whole thread is sleeping.

You can then also understand what happens if you block the main thread. No touch events, no system notifications, no nothing. It is all just kept in array and it will be called once the thread is unblocked and another loop occurs. The main loop also sends the date on each cycle which is then used for the watch dog. Since the OS works on another thread then your application it is the OS that will check that date and if it is relatively old you get to "application not responding" state. And then the OS may decide to kill your application.

Note that this is oversimplified but it is enough to get a basic understanding on how these things work.

Upvotes: 1

Related Questions