[iOS]runloop 輕量級實現LightWeightRunloop 源碼學習

Basic Information

  • Name : LightWeightRunLoop
  • Site : https://github.com/wuyunfeng/LightWeightRunLoop
  • Description :
    Using BSD kqueue realize iOS RunLoop and some Runloop-Relative Fundation API such as perform selector(or delay some times) on other thread , Timer, URLConnection etc..

Global Note

1.CFRunLoopRef 的代碼是開源的,你可以在這里
http://opensource.apple.com/tarballs/CF/CF-855.17.tar.gz
下載到整個 CoreFoundation 的源碼.

2.github 上搜runloop,選擇語言Objective-C,搜到43個結果
按照star排序,第一個就是這個,一個簡單版本的runloop

3.讀了源碼才明白這個其實相當于android的lopper一種實現方式,關于android的runloop和iOS的runloop的對比,可以參照這里
從安卓的Looper到iOS的RunLoop
http://www.lxweimin.com/p/7a970fc5343b

File Notes

屏幕快照 2016-04-21 上午1.03.04.png

1. LWSystemClock.m

  • Path : /LightWeightLibrary/LightWeightBasement/LWSystemClock.m
  • Line : 11 - 17
  • Note :
@implementation LWSystemClock

+ (NSInteger)uptimeMillions
{
    NSInteger now = (NSInteger)([NSProcessInfo processInfo].systemUptime * 1000);
    return now;
}

polen:
NSProcessInfo用于獲取當前正在執行的進程信息,包括設備的名稱,操作系統版本,進程標識符,進程環境,參數等信息。
e.g.

NSString *processName = [[NSProcessInfo processInfo] processName];

這里的LWSystemClock 是為了拿到系統從啟動開始運行的時間,和Unix時間戳是有區別的,可以說是一個相對時間

2. LWRunLoop.m

  • Path : /LightWeightLibrary/LightWeightBasement/LWRunLoop.m
  • Line : 44 - 54
  • Note :
+ (instancetype)currentLWRunLoop {
  int result = pthread_once(&mTLSKeyOnceToken, initTLSKey);
  NSAssert(result == 0, @"pthread_once failure");
  LWRunLoop* instance = (__bridge LWRunLoop*)pthread_getspecific(mTLSKey);
  if (instance == nil) {
    instance = [[[self class] alloc] init];
    [[NSThread currentThread] setLooper:instance];
    pthread_setspecific(mTLSKey, (__bridge const void*)(instance));
  }
  return instance;
}

polen:
通過currentLWRunLoop獲得當前線程的LWRunLoop
pthread_getspecific方法是C語言的方法,對應于pthread_setspecific用于線程存儲/讀取局部變量.
這個你可以理解為類似一個Dictionary,本例中的mTLSKey就是key,對應存儲一個value,然后需要的時候取出來這個value.
這個是屬于這個線程自己的局部變量,其他線程不可以訪問,這種機制稱之為

線程特有數據(TSD: Thread-Specific Data

或者 線程局部存儲(TLS: Thread-Local Storage).

okey,
show me the code:

//在Linux中提供了如下函數來對線程局部數據進行操作
#include <pthread.h>

*// Returns 0 on success, or a positive error number on error*
int pthread_key_create (pthread_key_t **key*, void (**destructor*)(void *));

*// Returns 0 on success, or a positive error number on error*
int pthread_key_delete (pthread_key_t *key*);

*// Returns 0 on success, or a positive error number on error*
int pthread_setspecific (pthread_key_t *key*, const void **value*);

*// Returns pointer, or NULL if no thread-specific data is associated with key*
void *pthread_getspecific (pthread_key_t *key*);

3. LWRunLoop.m

  • Path : /LightWeightLibrary/LightWeightBasement/LWRunLoop.m
  • Line : 56 - 65
  • Note :
#pragma mark run this loop forever
#LWRunLoop.m
- (void)run {
  while (true) {
    LWMessage* msg = [_queue next];
    @autoreleasepool {
      [msg performSelectorForTarget];//polen:下面有具體代碼
      [self necessaryInvocationForThisLoop:msg];//polen:下面有具體代碼
    }
  }
}

polen:
此為LWRunLoop類中的run方法,通過該方法讓_lwRunLoopThread這個線程進入 Event-Driver-Mode模式.

可以看到
從_queue中獲取到next Message,然后,循環執行對應的事件:
next,下一件,下一件,下一件... (循環下去...)

然后,我們再看while循環里的具體執行的操作:

# LWMessage.m
//1. 首先隊列中取到下一條消息,消息LWMessage去執行對應target的selector
- (void)performSelectorForTarget
{
    if (_mTarget == nil) {
        NSLog(@"------%@ is released !", _mTarget);
    }
    if ([_mTarget respondsToSelector:_mSelector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [_mTarget performSelector:_mSelector withObject:_mArgument];
#pragma clang diagnostic pop
    } else {
        NSLog(@"xxxxx %@", NSStringFromSelector(_mSelector));
    }
}

#LWRunLoop.m
//2. 消息執行完之后,runloop就會去檢查是否是定時器LWTimer,如果是定時器則采用定時器需要的一些檢查和操作
- (void)necessaryInvocationForThisLoop:(LWMessage*)msg {
  if ([msg.data isKindOfClass:[LWTimer class]]) {  // LWTimer: periodical
                                                   // perform selector
    LWTimer* timer = msg.data;
    if (timer.repeat) {
      msg.when = timer.timeInterval;  // must
      [self postMessage:msg];
    }
  }
}

4. NSObject+post.h

  • Path : /LightWeightFoundation/NSObject+post.h
  • Line : 11 - 43
  • Note :
@interface NSObject (post)

- (void)postSelector:(SEL)aSelector onThread:(NSThread *)thread withObject:(id)arg;

- (void)postSelector:(SEL)aSelector onThread:(NSThread *)thread withObject:(id)arg afterDelay:(NSInteger)delay;

- (void)postSelector:(SEL)aSelector onThread:(NSThread *)thread withObject:(id)arg afterDelay:(NSInteger)delay modes:(NSArray<NSString *> *)modes;

polen:
這個是個對NSObject的擴展
可以指定線程,指定方法,指定對象,指定模式,并在一定的延時時間之后執行.
這個庫對于使用者來說,可能最需要的就是這個3個方法:
根據自己的需求,讓所需要的方法在指定的線程中去延時(或者時時)執行

5. LWRunLoop.m

  • Path : /LightWeightLibrary/LightWeightBasement/LWRunLoop.m
  • Line : 19 - 23
  • Note :
NSString* const LWDefaultRunLoop = @"LWDefaultRunLoop";
NSString* const LWRunLoopCommonModes = @"LWRunLoopCommonModes";
NSString* const LWRunLoopModeReserve1 = @"LWRunLoopModeReserve1";
NSString* const LWRunLoopModeReserve2 = @"LWRunLoopModeReserve2";
NSString* const LWTrackingRunLoopMode = @"LWTrackingRunLoopMode";

polen:
LightWeightRunloop 中runloop 的mode,大致上面幾種
默認是在LWDefaultRunLoop,
可以對比下iOS中自己的runloop mode:

1. kCFRunLoopDefaultMode: App的默認 Mode,通常主線程是在這個 Mode 下運行的。
2. UITrackingRunLoopMode: 界面跟蹤 Mode,用于 ScrollView 追蹤觸摸滑動,保證界面滑動時不受其他 Mode 影響。
3. UIInitializationRunLoopMode: 在剛啟動 App 時第進入的第一個 Mode,啟動完成后就不再使用。
4: GSEventReceiveRunLoopMode: 接受系統事件的內部 Mode,通常用不到。
5: kCFRunLoopCommonModes: 這是一個占位的 Mode,沒有實際作用。

6. LWRunLoop.m

  • Path : /LightWeightLibrary/LightWeightBasement/LWRunLoop.m
  • Line : 78 - 81
  • Note :
- (void)changeRunLoopMode:(NSString*)targetMode {
  _currentRunLoopMode = targetMode;
  _queue.queueRunMode = _currentRunLoopMode;
}

polen:
切換當前runloop的mode,任何時間都可以切換

7. LWMessageQueue.h

  • Path : /LightWeightLibrary/LightWeightBasement/LWMessageQueue.h
  • Line : 12 - 54
  • Note :
@interface LWMessageQueue : NSObject
@property (nonatomic) NSString *queueRunMode;
@property (nonatomic, assign) BOOL allowStop;

+ (instancetype)defaultInstance;

- (BOOL)enqueueMessage:(LWMessage *)msg when:(NSInteger)when;
- (LWMessage *)next;
- (LWMessage *)next:(NSString *)mode;

7.1消息隊列

polen:
這個LWMessageQueue是消息隊列,每個runloop里面有個消息隊列_queue和runloop mode,如下,

@implementation LWRunLoop {
  LWMessageQueue* _queue;
  NSString* _currentRunLoopMode;
}

從第3條( LWRunLoop.m)可以看出來, runloop執行的時候,就是靠自己的消息隊列,將一條條消息取出來執行掉。

不想網上翻頁的童鞋,我把代碼再貼一遍:

#LWRunLoop.m
- (void)run {
  while (true) {
     //這里面不斷循環取下一條,下一條...
    LWMessage* msg = [_queue next];
    @autoreleasepool {
      [msg performSelectorForTarget];
      [self necessaryInvocationForThisLoop:msg];
    }
  }
}

7.2 next 消息

來看一下消息隊列獲取next 消息的代碼:

- (LWMessage*)next {
  NSInteger nextWakeTimeoutMillis = 0;
  while (YES) {
    [_nativeRunLoop nativeRunLoopFor:nextWakeTimeoutMillis];
    @synchronized(self) {
      NSInteger now = [LWSystemClock uptimeMillions];
      LWMessage* msg = _messages;
      if (msg != nil) {
        if (now < msg.when) {
          //polen:獲取下次喚醒時間
          nextWakeTimeoutMillis = msg.when - now;
        } else {
           //polen:當前狀態ok,可獲取到下一條消息
          _isCurrentLoopBlock = NO;
          _messages = msg.next;
          msg.next = nil;
          return msg;
        }
      } else {
        nextWakeTimeoutMillis = -1;
      }
      //polen:完成了 
      _isCurrentLoopBlock = YES;
    }
  }
}

polen:
@synchronized(self) 是為了保證線程安全, 代碼的邏輯還是比較清晰的,如果message的待執行時間還未到,就獲取下次喚醒時間nextWakeTimeoutMillis,如果已經到了,則還是執行,并將該runloop的_messages指向next消息(準備下一輪的執行)

其中關鍵的是這一端代碼:

while (YES) {
  [_nativeRunLoop nativeRunLoopFor:nextWakeTimeoutMillis];
  ...
}

//polen:點進去詳情是這樣的
- (void)nativeRunLoopFor:(NSInteger)timeoutMillis {
  struct kevent events[MAX_EVENT_COUNT];
  struct timespec* waitTime = NULL;
  if (timeoutMillis == -1) {
    waitTime = NULL;
  } else {
    waitTime = (struct timespec*)malloc(sizeof(struct timespec));
    waitTime->tv_sec = timeoutMillis / 1000;
    waitTime->tv_nsec = timeoutMillis % 1000 * 1000 * 1000;
  }
  int ret = kevent(_kq, NULL, 0, events, MAX_EVENT_COUNT, waitTime);
  NSAssert(ret != -1, @"Failure in kevent().  errno=%d", errno);
  free(waitTime);
  waitTime = NULL;  // avoid wild pointer
  for (int i = 0; i < ret; i++) {
    int fd = (int)events[i].ident;
    int event = events[i].filter;
    if (fd == _mReadPipeFd) {  // for pipe read fd
      if (event & EVFILT_READ) {
        //polen:EVFILT_READ 下面會解釋
        // must read mReadWakeFd, or result in readwake always wake
        [self nativePollRunLoop];
      } else {
        NSLog(@"other event happend.");
      }
    }
  }
}

polen:
這個其實就是讀取事件列表的事情了,里面有幾個重要的點:

7.2.1 kevent函數

int ret = kevent(_kq, NULL, 0, events, MAX_EVENT_COUNT, waitTime);

說明下:第一個參數_kq是LWNativeLoop結構中的消息隊列

//基本的類型結構
@implementation LWNativeLoop {
  int _mReadPipeFd; //polen:pip 管道的讀端
  int _mWritePipeFd;//polen:pip 管道的寫端
  int _kq; //polen:對,就是這個
  NSMutableArray* _fds;
}

// 初始化函數里面有:
  _kq = kqueue();
  NSAssert(_kq != -1, @"Failure in kqueue().  errno=%d", errno);

polen:

利用Linux系統中的管道(pipe)進程間通信機制來實現消息的等待和處理。通過kevent函數可以知道剩余消息事件的個數值ret,從而遍歷這些消息. runloop的等待就是通過這個函數實現的,如果waitTime不是null,則會等待waitime,如果為null,kevent將會阻塞,一直等待直到有事件發生為止...

|
p.s. 關于kevent的說明:

kevent函數用于和kqueue的交互。第一個參數是kqueue返回的描述符。changelist參數是一個大小為nchanges的 kevent結構體數組。changelist參數用于注冊或修改事件,并且將在從kqueue讀出事件之前得到處理。

eventlist 參數是一個大小為nevents的kevent結構體數組。kevent通過把事件放在eventlist參數中來向調用進程返回事件。如果需要的 話,eventlist和changelist參數可以指向同一個數組。最后一個參數是kevent所期待的超時時間。如果超時參數被指定為 NULL,kevent將阻塞,直至有事件發生為止。如果超時參數不為NULL,則kevent將阻塞到超時為止。如果超時參數指定的是一個內容為0的結 構體,kevent將立即返回所有當前尚未處理的事件。

kevent的返回值指定了放在eventlist數組中的事件的數目。如果事件 數目超過了eventlist的大小,可以通過后續的kevent調用來獲得它們。在處理事件的過程中發生的錯誤也會在還有空間的前提下被放到 eventlist參數中。帶有錯誤的事件會設置EV_ERROR位,系統錯誤也會被放到data成員中。對于其它的所有錯誤都將返回-1,并相應地設置 errno。

針對這個查了下android對應runloop的實現代碼:

#ifdef LOOPER_USES_EPOLL  
    struct epoll_event eventItems[EPOLL_MAX_EVENTS];  
    int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);  
    bool acquiredLock = false;  
#else  
    ......  
#endif  

一看一目了然,epoll_wait 和 我們的kevent是一樣一樣的...
http://blog.csdn.net/luoshengyang/article/details/6817933/

老羅語錄 (羅升陽):
首先是調用epoll_wait函數來看看epoll專用文件描述符mEpollFd所監控的文件描述符是否有IO事件發生,它設置監控的超時時間為timeoutMillis
當mEpollFd所監控的文件描述符發生了要監控的IO事件后或者監控時間超時后,線程就從epoll_wait返回了,否則線程就會在epoll_wait函數中進入睡眠狀態了。返回后如果eventCount等于0,就說明是超時了.

7.2.2 EVFILT_READ

polen:
接著往后看

if (event & EVFILT_READ) {
        // must read mReadWakeFd, or result in readwake always wake
        [self nativePollRunLoop];
}else{ 
        ... 
} 

kevent結束之后,后面是事件的讀操作,里面判斷條件有一句EVFILT_READ這個,EVFILT_READ是什么東西呢?

EVFILT_READ過濾器用于檢測什么時候數據可讀。kevent的ident成員應當被設成一個有效的描述符。盡管這個過濾器的行為和select 或這poll很像,但它返回的事件將是特定于所使用的描述符的類型的。

7.2.3 關于管道pip

#pragma mark - Process two fds generated by pipe()
- (void)nativeWakeRunLoop {
  ssize_t nWrite;
  do {
    nWrite = write(_mWritePipeFd, "w", 1);
  } while (nWrite == -1 && errno == EINTR);

  if (nWrite != 1) {
    if (errno != EAGAIN) {
      NSLog(@"Could not write wake signal, errno=%d", errno);
    }
  }
}

- (void)nativePollRunLoop {
  char buffer[16];
  ssize_t nRead;
  do {
    nRead = read(_mReadPipeFd, buffer, sizeof(buffer));
  } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
}

polen:
這里面消息循環和處理的代碼實現是基于pip的,不過只有親自看源碼,才能明白其中的要以,不想看源碼,只想知道原理的,

可以直接參照我們牛逼的老羅同學(羅升陽)語錄:
http://blog.csdn.net/luoshengyang/article/details/6817933/
管道是Linux系統中的一種進程間通信機制,具體可以參考前面一篇文章Android學習啟動篇推薦的一本書《Linux內核源代碼情景分析》中的第6章--傳統的Uinx進程間通信。
簡單來說,管道就是一個文件,在管道的兩端,分別是兩個打開文件文件描述符,這兩個打開文件描述符都是對應同一個文件,其中一個是用來讀的,別一個是用來寫的,一般的使用方式就是,一個線程通過讀文件描述符中來讀管道的內容,當管道沒有內容時,這個線程就會進入等待狀態,而另外一個線程通過寫文件描述符來向管道中寫入內容,寫入內容的時候,如果另一端正有線程正在等待管道中的內容,那么這個線程就會被喚醒。
這個等待和喚醒的操作是如何進行的呢?
這就要借助Linux系統中的epoll機制了。
Linux系統中的epoll機制為處理大批量句柄而作了改進的poll,是Linux下多路復用IO接口select/poll的增強版本,它能顯著減少程序在大量并發連接中只有少量活躍的情況下的系統CPU利用率。但是這里我們其實只需要監控的IO接口只有mWakeReadPipeFd一個,即前面我們所創建的管道的讀端,為什么還需要用到epoll呢?有點用牛刀來殺雞的味道。其實不然,這個Looper類是非常強大的,它除了監控內部所創建的管道接口之外,還提供了addFd接口供外界面調用,外界可以通過這個接口把自己想要監控的IO事件一并加入到這個Looper對象中去,當所有這些被監控的IO接口上面有事件發生時,就會喚醒相應的線程來處理,不過這里我們只關心剛才所創建的管道的IO事件的發生。

Summarize

看的有點累,不過學了不少東西...

另,
1.想補充下基礎runloop知識的同學,可以看看這里
[iOS]runloop - iOS界的EventLoop
http://www.lxweimin.com/p/033087def3a4

2.想知道這篇文章格式是怎么出來的,請下載插件 XSourceNote ,這個是我們的everettjf同學寫的,用起來也是很舒服??


by polen

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 前言 最近離職了,可以盡情熬夜寫點總結,不用擔心第二天上班爽并蛋疼著,這篇的主角 RunLoop 一座大山,涵蓋的...
    zerocc2014閱讀 12,435評論 13 67
  • Runloop是iOS和OSX開發中非常基礎的一個概念,從概念開始學習。 RunLoop的概念 -般說,一個線程一...
    小貓仔閱讀 1,024評論 0 1
  • 先貼下 apple doc, 本文基本是對照 doc 的翻譯:https://developer.apple.co...
    brownfeng閱讀 6,923評論 8 111
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,981評論 19 139
  • 我想我們都是一塊塊普普通通的石頭,不,不是普通的,而是以幾乎支離破碎的姿態,離開那座萬古的磐石高山。看啊!滿布的隱...
    William王漢閱讀 247評論 0 0