2

I just read on this answer(answer has since been removed) and I'm sure I've seen apps crash after hanging so what I read made sense.

If you block the main thread for too long the OS will kill your app.


However I wrote a few tests and found that none of them caused the app to crash after waiting approx 2-5 mins on each. Breakpoints confirmed that I'm running on the main thread.

  • Can someone confirm or disprove what I read please or have I just picked a lot of options which are non-blocking?

  • If I have picked non blocking options, can somebody explain why these are non-blocking?


while (true) { /*Nothing*/ }

while (true) { NSLog(@"nothing"); }

for(;;);

sleep(100000000);

while(true) { sleep(1); }
Community
  • 1
  • 1
James Webster
  • 31,873
  • 11
  • 70
  • 114

2 Answers2

2

iOS will only kill your app if it spends too long in some of the UIApplicationDelegate methods like application:didFinishLaunchingWithOptions: or applicationDidEnterBackground:. You usually have 5 seconds to return, although this is not enforced for debug versions of your application.

Blocking the main thread outside of these methods will not cause your application to be terminated.

Mike Weller
  • 45,401
  • 15
  • 131
  • 151
  • Thank you. Is the code I wrote blocking? The other answer seems to suggest no. – James Webster Jun 13 '12 at 14:55
  • It depends on what you mean by blocking. When each of the lines you posted is executed by a thread, that thread will get stuck there and not move on. Although technically the `sleep(100000000);` line will return after 1157 days. – Mike Weller Jun 13 '12 at 15:04
  • 1
    I've got some waiting to do then! Thanks for the clarification. – James Webster Jun 13 '12 at 15:20
0

The answer that you are referring is not correct, the crash is because he runs out of memory, not because he blocks the main thread. I believe that none of the examples that you've given block the thread. The way to really block the thread would be to use recursion, or call dispatch_sync from the main thread with main queue as argument. This would create the deadlock but I don't think your application will be terminated because of that (though I can be wrong).

So why are these non blocking? Depends how you define blocking. All of the examples that you provided except 4th only prevent your code from progressing to the next line, which is perfectly ok. The sleep(10000000) is even weaker than this because it will properly return after given amount of seconds, so why would this cause any trouble?

lawicko
  • 7,246
  • 3
  • 37
  • 49
  • Yeah, I wrote the other answer to that question. But interesting to realise that I wasn't blocking anyway – James Webster Jun 13 '12 at 14:52
  • 2
    They do block the thread from proceeding. Not all of them block in the sense that the thread is non-executable, although the sleeps do. Some of them block by busy-looping forever. – Ken Thomases Jun 13 '12 at 14:59