21.10 · The main thread in code: hang watchdogs, actor hops and quality of service

The main-thread contract is easy to state and easy to break. You can measure the break from inside the process, and the cost of moving work off the main thread is not zero.

Mental model. Detect stalls with a heartbeat, hop deliberately, and tag work with the quality of service it deserves.

Detecting and moving work

A watchdog for hangs, and what an actor hop costs.

  1. How can an app detect its own main-thread hangs, and what are the limits of doing it in-process? 21.10.1 · L5
    A watchdog is a background thread that repeatedly asks the main queue to record a heartbeat (DispatchQueue.main.async { lastPong = now }), sleeps briefly, and…
  2. Is moving work off the main actor free, and what does it cost to hop back to it many times? 21.10.2 · L5
    Calling a @MainActor function from another task is a suspension plus an enqueue: the caller gives up its thread, the work is queued on the main executor, and…

More in Performance & energy