Tuesday, 3 November 2015

Run Loop


“Run loops are part of the fundamental infrastructure associated with threads. A run loop is an event processing loop that you use to schedule work and coordinate the receipt of incoming events. The purpose of a run loop is to keep your thread busy when there is work to do and put your thread to sleep when there is none.” -Threading Programming Guide: “Run Loops”, Apple Inc.


Put simply, a run loop is a messaging mechanism, used for asynchronous or interthread communication. It can be seen as a post box that waits for messages and delivers them to recipients.
A run loop does two things:
  • wait until something happens (e.g., a message arrives),
  • dispatch that message to its receiver.
On other platforms, this mechanism is called the “Message Pump”.


Run loops are what separates interactive apps from command-line tools. Command-line tools are launched with parameters, execute their command, then exit. Interactive apps wait for user input, react, then resume waiting. In fact, this basic mechanism is found in pretty much every long-lived process. A good old while(1){select();}in a server is a run loop.

The job of a run loop is to wait for things to happen. Those things can be external events, caused by the user or the system (e.g. a network request.) or internal app messages, like inter-thread notifications, asynchronous code execution, timers… Once an event (or a “message”) is received, the run loop finds a relevant listener and pass it the message.

Its main purpose is keeping the thread from exit when it is still needed, but only actively handle the events when the events are arrived.For the main thread, the ios system will create a RunLoop automatically after starting the app, so the application can keep running.


How runloop works:

  • It takes all input events,
  • Keeps them in runloop stack,
  • Fires one at a time,
  • Gives events to handlers to process (input data as events, callback methods as handlers for Connection object),
  • Waits till that event gets completed,
  • Once complete return back to runloop stack,
  • Check for another event to process,
  • If none is there goes to sleep.
– Basically, It sends asynchronous callbacks to handlers, if we don’t want remove / invalidate object from runloop.
– They must be associated at least one mode, because modes determines what event should processed.
– Scheduling a run loop source doesn’t allow the source’s callbacks to run concurrently with other source’s callbacks.

No comments:

Post a Comment