iosobjective-cmacosrunloop

Difference between CFRunloopRun() and a simple infinite loop?


I schedule a HIDManager on the current runloop, which is the runloop for the main function.

When I add the following line

CFRunLoopRun();

All HID events will be captured and the output will be shown on the screen, which is compatible with the Runloop Model

enter image description here

But if I add a

for(;;);

at the end of the main loop, from my understanding, I can also keep this runloop exist and the thread will never die. Why I cannot receive any HID events and nothing got printed on the screen right now?


Solution

  • CFRunLoopRun() works different from a simple infinite loop, as it pauses the execution of the program and waits for new events to arrive, which could either be timers firing, HID events, etc. When you call CFRunLoopRun(), you will notice that the CPU usage of your program drops to zero as long as no new events arrive.

    By running an infinite loop inside the thread that your run loop is on, your program is busy running that infinite loop and it has no time to process new events.