2

If each UIApplication initializes a RunLoop like this on the main thread

void CFRunLoopRun(void) {   /* DOES CALLOUT */
    int32_t result;
    do {
        result = CFRunLoopRunSpecific(CFRunLoopGetCurrent(), kCFRunLoopDefaultMode, 1.0e10, false);
        CHECK_FOR_FORK();
    } while (kCFRunLoopRunStopped != result && kCFRunLoopRunFinished != result);
}

Why it doesn't block the whole execution since it is an infinite loop? How could an infinite loop and my code on the main thread work together on a single thread without context switching?

Patroclus
  • 1,163
  • 13
  • 31
  • 3
    Because your code 'on the main thread' is running inside the runloop. All UIApplication events are delivered via the runloop (or dispatch, which also is scheduled into the runloop, via some magic), which means, all of your code is running inside the call to `CFRunLoopRunSpecific`. You can verify this by looking at the call stack during any UIEvent that gets triggered in your application. – Richard J. Ross III Aug 12 '19 at 21:44
  • @RichardJ.RossIII How to better understand the whole structure of a UIApplication? Apple doesn't provide very detailed documentation on how it is structured. Would you prefer to dig into the call stack and learn from it? – Patroclus Aug 12 '19 at 21:49
  • 1
    This part of the system isn't iOS specific, and is documented primarily in the OS X Cocoa docs. Apple has been deprecating their foundational documentation for years now, so it has become much harder to find up-to-date documentation of these kinds of details unless you already know the specific doc you're looking for (and sometimes, they're hard to find even then). https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html – Rob Napier Aug 12 '19 at 22:44

1 Answers1

2

It does block the current thread. However, part of what CFRunLoopRunSpecific does is call your code on that thread. When you return, it goes back to CFRunLoopRunSpecific, which then calls other code.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610