3

I have been reading about RunLoops for a few days in Apple documentation and stuff from Google search. I have understood the concept of RunLoops to great extent but still I got no answer to some basic questions regarding RunLoops.

  1. How Runloop exactly works ? Is it something like while loop running at some system level ?
  2. If it is indeed some sort of while loop at some system level, then how does it differ from polling ?

Please provide me with some pointers for this..

tek3
  • 2,095
  • 2
  • 20
  • 50

1 Answers1

6

The whole point about a RunLoop (variously named as Window Handler, main-loop, event-loop on other platforms) is that it facilitates an Event Driven Architecture in which an application only runs when there is something to do - for example, responding to user-interaction. This is the opposite of polling.

Fundamental to the architecture is a some kind of message queue that a thread can block on until a message available for processing. On MacOSX and iOS systems the queue is a Mach kernel RPC port. On Windows it's a kernel IPC queue, and X-windows systems, a unix-domain or network socket.

Events are inserted into the queue by other system components - for instance a Window Manager and other applications. It is also common for applications to message themselves from other threads in order to perform all UI processing in the same thread.

The run-loop itself resides in application space and looks something like this:

while (!stop)
{
    message = WaitForNextMessage();
    DispatchMessage(message);
}

Usually, whatever UI framework you use provides a mechanism for registering an event handler for particular types of events.

marko
  • 9,029
  • 4
  • 30
  • 46
  • Thanks a lot for your response. Your answer has indeed cleared my concept of RunLoops. But I think I need to dig further down and read about what you mentioned in your answer Event Driven Architecture. – tek3 Aug 17 '13 at 12:24