Preface
RunLoop is a concept that has already been explained many times. Many excellent developers have written about their own understanding of it, and I have read quite a few of those articles with real admiration, for example:
Even so, I always felt that my understanding of RunLoop was still a little blurry. The veil had not been fully lifted, especially because a lot of what I knew came from hearing other people explain it.
A RunLoop is essentially a large event-driven loop. Event-driven loops exist in many languages. In pseudocode, it looks like this:
1 | int main(int argc, char * argv[]) { |
Sometimes I wonder: if I tried to implement a simple, homemade version of RunLoop based on my own learning and understanding, what should it look like?
- Since a RunLoop is, well, a loop, the first thing should be an endless loop.
- It should also have its own event queue. Whenever an event occurs, the event is pushed into the queue, and each loop iteration takes one event out and handles it.
- When the queue is empty, the thread running the RunLoop should sleep. When a new event arrives, that thread should be woken up. With my limited knowledge, I can only think of I/O multiplexing as the mechanism that solves this.
- A RunLoop should distinguish Timer, Observer, Source, and other concepts.
- …
While collecting references, I unexpectedly found a project called LightWeightRunLoop-A-Reactor-Style-NSRunLoop. It felt exactly like finding what I had been looking for. After reading it carefully, I found that its overall idea matched my own mental model quite well. So in this article, I will use its source code to analyze how a lightweight RunLoop can be implemented. Many thanks to the author, wuyunfeng.
Overall Structure
LightWeightRunLoop implements several RunLoop-related
APIs, such as PerformSelector, Timer,
URLConnection, LWStream, and
LWPort. The goal of this article is not to explain how to
use these APIs, but to understand how they are implemented internally,
and use that to deepen our understanding of RunLoop.
Borrowing the author’s diagram:
LWRunLoop
How a Thread Gets an LWRunLoop Object
Every thread except the main thread can have an
LWRunLoop object. It can be obtained by calling
[LWRunLoop currentLWRunLoop] on the running thread:
1 | NSThread *_lwRunLoopThread = [[NSThread alloc] initWithTarget:self selector:@selector(lightWeightRunloopThreadEntryPoint:) object:nil]; |
Internal Implementation of currentLWRunLoop
Let’s look at the internal implementation of
currentLWRunLoop:
1 | + (instancetype)currentLWRunLoop |
From the source code, we can see that the thread’s
LWRunLoop object is stored as thread-specific data, or TSD,
through pthread_setspecific and
pthread_getspecific. Next, look at the initialization
function of LWRunLoop. It simply initializes a message
queue of type LWMessageQueue.
1 | - (instancetype)init |
How LWRunLoop Runs
Now look at the implementation of the run function in
LWRunLoop:
1 | - (void)run |
The idea is straightforward: in each loop iteration, take one message from the message queue and execute the corresponding event.
1 | - (void)performSelectorForTarget |
1 | // Periodic LWTimer needs special handling. |
LWMessageQueue
How to Get LWMessageQueue
1 | + (instancetype)defaultInstance |
Clearly, this follows the same pattern as getting
LWRunLoop, so there is no need to repeat the details.
LWMessageQueue Initialization
1 | - (instancetype)init |
Two important things happen here:
- It defines a
LWNativeRunLoop, which is related to the kernel mechanism mentioned earlier: I/O multiplexing.LWNativeRunLoopis the core ofLWRunLoop, and it is the foundation that lets this loop actually run.- It observes changes to the RunMode. Once the mode changes, it calls
LWNativeRunLoopto wake up the kernel.
1 | - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context |
Enqueuing Messages in LWMessageQueue
1 | - (BOOL)enqueueMessage:(LWMessage *)msg when:(NSInteger)when |
The enqueue method takes two parameters: the message itself and the time when the message should fire. The storage structure is a linked list. First it looks at the head of the list.
- If the head is empty, or if the new message should fire earlier than the current head, the new message becomes the head.
- Otherwise, it walks the linked list and finds the first message whose firing time is later than the new one, then inserts the new message before it.
Finally, if the current thread is blocked, it calls
nativeWakeRunLoop to wake it up.
Dequeuing Messages from LWMessageQueue
1 | - (LWMessage *)next:(NSString *)mode |
First, it obtains the messages that need to be handled from
nativeRunLoopFor.
- If there is no message, it marks the current thread as blocked.
- If the message matches the current thread’s RunMode, it checks its
firing time. If the firing time is less than or equal to the current
time, it removes the message from the queue and returns it. Otherwise,
it simply sets
nextWakeTimeoutMillisas the wake-up timeout. - If the message does not match the current RunMode, it stores that message in a separate queue for messages that missed the current mode, so it can be used later when the RunMode changes.
LWNativeRunLoop: The Core
After reading the code above, it still feels like we have not touched
the real core. As mentioned earlier, LWNativeRunLoop is the
foundation and the key part of the whole system. So let’s analyze why it
matters so much.
- Note: before reading this part, it helps to have some background knowledge of I/O multiplexing.
LWNativeRunLoop Initialization
1 | - (instancetype)init |
1 | - (void)prepareLWRunLoop |
The kqueue system has three important pieces: the
struct kevent structure, the EV_SET macro, and
the kevent function.
- The
struct keventstructure looks like this:
1 | struct kevent { |
EV_SETis a convenience macro used to initialize akeventstructure. Its signature is:
1 | EV_SET(&kev, ident, filter, flags, fflags, data, udata); |
It maps exactly to the fields of the kevent structure.
The first argument is the kevent structure you want to
initialize.
keventis the actual function that performs I/O multiplexing. Its signature is:
1 | int kevent(int kq, |
Overall, prepareLWRunLoop mainly monitors the
_mReadPipeFd file descriptor.
The Magical nativeRunLoopFor
The key method nativeRunLoopFor appears many times
above. Let’s focus on it:
1 | - (void)nativeRunLoopFor:(NSInteger)timeoutMillis |
For now, we only care about the _mReadPipeFd file
descriptor. Once it matches, nativePollRunLoop is
called:
1 | - (void)nativePollRunLoop |
In nativePollRunLoop, the data read into
buffer is simply discarded. Some people may ask: why do
something that looks unnecessary?
Think about it this way: if one end of a pipe has data to read, then data must have been written to the other end:
1 | - (void)nativeWakeRunLoop |
See it? The method name says exactly what it does.
Before a monitored file descriptor becomes ready, or before
the timeout expires, kevent keeps the thread blocked, or
asleep, so it no longer consumes CPU time. That means we do not care
what data is actually sent or received through the pipe. What matters is
that this write-and-read action directly wakes the RunLoop, allowing it
to continue processing messages. With kevent handling
blocking sleep, and with the pipe used here for wake-up, though other
wake-up mechanisms are also possible, a thread’s RunLoop takes
shape.
NSObject
Look at the postSelector here, and imagine how
performSelector can be implemented:
1 | - (void)postSelector:(SEL)aSelector onThread:(NSThread *)thread |
1 | - (void)postTarget:(id)target withAction:(SEL)aSel withObject:(id)arg afterDelay:(NSInteger)delayMillis |
LWTimer
It follows the same pattern. Read it and you can feel the idea directly:
1 | + (LWTimer *)scheduledLWTimerWithTimeInterval:(NSTimeInterval)interval target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo |
1 | - (void)postMessage:(LWMessage *)msg |