Sobes.tech
Middle

What is a run loop?

sobes.tech AI

Answer from AI

The run loop is the main event processing loop in an application. It allows scheduling work and coordinating incoming events (from users, network, timers, etc.) in a specific thread.

Key concepts:

  • Threads: Each thread has its own run loop, but it does not start automatically, except for the main application thread.
  • Input Sources: Generate events. They can be Port-based (system events) or Custom (user events).
  • Timers: Generate events at specific times or intervals.
  • Observers / Callbacks: Allow receiving notifications about various events in the run loop's lifecycle.
  • Modes: Define which input sources and timers are monitored by the run loop at any given time. The most commonly used are:
    • defaultMode: The main mode.
    • trackingMode: Used during UIViews scrolling or other activities requiring priority over regular events.

How it works:

The run loop goes into a "sleeping" state when there are no pending events and wakes up when sources become active. It then processes events and can go back to sleep if there is no further work.

Example of starting a run loop for a secondary thread:

// Example of starting a run loop for the current thread
// Never returns until explicitly stopped
let runLoop = RunLoop.current
runLoop.run()

Example of starting a run loop for a specific period:

// Example of running the run loop for 5 seconds
RunLoop.current.run(mode: .default, before: Date.now.addingTimeInterval(5))

Main functions:

  • Receiving and processing events.
  • Performing deferred work.
  • Coordinating work across multiple threads.
  • Saving energy (without active polling of events).
What is a run loop? — iOS - sobes.tech