IOS多线程编程指南二之Runloop

一、什么是Runloop


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.
runloop就是帮组你间歇性的执行相关的任务,处理不同的事件的一个死循环。它可以使你的线程当有工作任务时运行,任务完成时便进入线程。
Your application does not need to create these objects explicitly; each thread, including the application’s main thread, has an associated run loop object. Only secondary threads need to run their run loop explicitly, however. The app frameworks automatically set up and run the run loop on the main thread as part of the application startup process.
每个线程都有自己相关联的runloop对象,不需要你单独去创建。主线程的runloop在应用启动时便会自动运行,而其他子线程的的runloop需要你调用run函数运行。

二、runloop的实质


A run loop is very much like its name sounds. It is a loop your thread enters and uses to run event handlers in response to incoming events. Your code provides the control statements used to implement the actual loop portion of the run loop — in other words, your code provides the while or for loop that drives the run loop. Within your loop, you use a run loop object to "run” the event-processing code that receives events and calls the installed handlers.
简单来说就是一个for或while创建的死循环,根据不同的事件响应对应的事件处理函数。

A run loop receives events from two different types of sources. Input sources deliver asynchronous events, usually messages from another thread or from a different application. Timer sources deliver synchronous events, occurring at a scheduled time or repeating interval. Both types of source use an application-specific handler routine to process the event when it arrives.
runloop的处理事件类型大致来说可以分为两类:

  1. 第一类Input sources通常是来自其他线程或者应用发过来的消息
  2. 第二类Timer sources由周期的定时器引起。

下图展示了runloop的大致结构和相关的事件类型input sources传输异步事件给runloop相应的处理函数并会调用runUntilDate:函数退出当前runloop。time sources传输同步事件给runloop相应的处理函数,不同的是并不会退出当前runloop。

IOS多线程编程指南二之Runloop_第1张图片

In addition to handling sources of input, run loops also generate notifications about the run loop’s behavior. Registered run-loop observers can receive these notifications and use them to do additional processing on the thread. You use Core Foundation to install run-loop observers on your threads.

除了上图体现的用不同的函数处理不同的输入事件的类型,还可以通过注册runloop不同状态的通知,来实现附加不同状态下处理函数的目的。

2.1 Run Loop Modes

你可能感兴趣的:(IOS多线程编程指南二之Runloop)