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:
- runloop runs at a specific interval
- runloop is done running, our code runs
- our code is done running, go to (1) (What if our code runs so long that runloop doesn't get a chance to run?)
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).
The runloop receives events from multiple sources and it handles those events. So, sending code to the main thread and/or pressing a button adds an event to the main runloop event queue and that event is handled when the runloop check its sources again. It doesn't suspend/lock in the middle of executing the current event.
Edit: seeing your edit, allow me to make this clarification: the runloop works with the main thread. The project template adds the runloop into our code and the runloop works with the tread to run the code. So "runloop is done running, our code runs" is incorrect, it's more like "the runloop receives an event from one of its sources telling it to run our code in this particular part".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With