Search code examples
iosobjective-cmultithreadingnsrunloop

Objective-C: How does code in main thread and its runloop interact?


How does code in main thread and its runloop interact? For example, does all code in main thread have to run until it is idle before hitting the runloop? Or does runloop check its sources in the middle of executing the code in main thread? Is it possible for runloop source to block main thread code from executing (since it's running on the same thread)?

I am trying to understand how main thread code fits into the picture of runloop (or vice versa) in the grand scheme of things.

Is this how a runloop looks like alongside our code:

Main thread:

  1. runloop runs at a specific interval
  2. runloop is done running, our code runs
  3. our code is done running, go to (1) (What if our code runs so long that runloop doesn't get a chance to run?)

Solution

  • You asked:

    How does code in main thread and its runloop interact?

    The main runloop is just a loop that is being performed on the main thread.

    What if our code runs so long that runloop doesn't get a chance to run?

    If you block the main thread (i.e. you do something synchronously that is very slow) then the runloop, which called your code and is waiting for you to return, will not have a chance to continue looping, and thus everything contingent upon that (timers, sources, UI, etc.) will appear to freeze.

    This is why, if you have any task that is going to take more than a few milliseconds, that you should dispatch it to some background queue, and get it off the main thread, and thus your code on the main thread can promptly return to the run loop and ensure that the main thread is not blocked. This will thereby ensure that the main runloop can continue operating and yield a responsive UI.

    In terms of your three points in which you describe how the runloop works, I might describe it differently. It's not that the runloop "ends" and then your code runs. It's really that the runloop is looping, handling various system events (e.g. UI, timers, etc.) and that, in the process of handling those, it may end up calling your code (in which case the whole main thread, including the runloop, is blocked from proceeding until your code returns back to the runloop).