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
下載到整個(gè) CoreFoundation 的源碼.
2.github 上搜runloop,選擇語(yǔ)言O(shè)bjective-C,搜到43個(gè)結(jié)果
按照star排序,第一個(gè)就是這個(gè),一個(gè)簡(jiǎn)單版本的runloop
3.讀了源碼才明白這個(gè)其實(shí)相當(dāng)于android的lopper一種實(shí)現(xiàn)方式,關(guān)于android的runloop和iOS的runloop的對(duì)比,可以參照這里
從安卓的Looper到iOS的RunLoop
http://www.lxweimin.com/p/7a970fc5343b
File Notes
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用于獲取當(dāng)前正在執(zhí)行的進(jìn)程信息,包括設(shè)備的名稱,操作系統(tǒng)版本,進(jìn)程標(biāo)識(shí)符,進(jìn)程環(huán)境,參數(shù)等信息。
e.g.
NSString *processName = [[NSProcessInfo processInfo] processName];
這里的LWSystemClock 是為了拿到系統(tǒng)從啟動(dòng)開始運(yùn)行的時(shí)間,和Unix時(shí)間戳是有區(qū)別的,可以說是一個(gè)相對(duì)時(shí)間
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獲得當(dāng)前線程的LWRunLoop
pthread_getspecific方法是C語(yǔ)言的方法,對(duì)應(yīng)于pthread_setspecific用于線程存儲(chǔ)/讀取局部變量.
這個(gè)你可以理解為類似一個(gè)Dictionary,本例中的mTLSKey就是key,對(duì)應(yīng)存儲(chǔ)一個(gè)value,然后需要的時(shí)候取出來這個(gè)value.
這個(gè)是屬于這個(gè)線程自己的局部變量,其他線程不可以訪問,這種機(jī)制稱之為
線程特有數(shù)據(jù)(TSD: Thread-Specific Data
或者 線程局部存儲(chǔ)(TLS: Thread-Local Storage).
okey,
show me the code:
//在Linux中提供了如下函數(shù)來對(duì)線程局部數(shù)據(jù)進(jìn)行操作
#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:
此為L(zhǎng)WRunLoop類中的run方法,通過該方法讓_lwRunLoopThread這個(gè)線程進(jìn)入 Event-Driver-Mode模式.
可以看到
從_queue中獲取到next Message,然后,循環(huán)執(zhí)行對(duì)應(yīng)的事件:
next,下一件,下一件,下一件... (循環(huán)下去...)
然后,我們?cè)倏磜hile循環(huán)里的具體執(zhí)行的操作:
# LWMessage.m
//1. 首先隊(duì)列中取到下一條消息,消息LWMessage去執(zhí)行對(duì)應(yīng)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. 消息執(zhí)行完之后,runloop就會(huì)去檢查是否是定時(shí)器LWTimer,如果是定時(shí)器則采用定時(shí)器需要的一些檢查和操作
- (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:
這個(gè)是個(gè)對(duì)NSObject的擴(kuò)展
可以指定線程,指定方法,指定對(duì)象,指定模式,并在一定的延時(shí)時(shí)間之后執(zhí)行.
這個(gè)庫(kù)對(duì)于使用者來說,可能最需要的就是這個(gè)3個(gè)方法:
根據(jù)自己的需求,讓所需要的方法在指定的線程中去延時(shí)(或者時(shí)時(shí))執(zhí)行
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,大致上面幾種
默認(rèn)是在LWDefaultRunLoop,
可以對(duì)比下iOS中自己的runloop mode:
1. kCFRunLoopDefaultMode: App的默認(rèn) Mode,通常主線程是在這個(gè) Mode 下運(yùn)行的。
2. UITrackingRunLoopMode: 界面跟蹤 Mode,用于 ScrollView 追蹤觸摸滑動(dòng),保證界面滑動(dòng)時(shí)不受其他 Mode 影響。
3. UIInitializationRunLoopMode: 在剛啟動(dòng) App 時(shí)第進(jìn)入的第一個(gè) Mode,啟動(dòng)完成后就不再使用。
4: GSEventReceiveRunLoopMode: 接受系統(tǒng)事件的內(nèi)部 Mode,通常用不到。
5: kCFRunLoopCommonModes: 這是一個(gè)占位的 Mode,沒有實(shí)際作用。
6. LWRunLoop.m
- Path : /LightWeightLibrary/LightWeightBasement/LWRunLoop.m
- Line : 78 - 81
- Note :
- (void)changeRunLoopMode:(NSString*)targetMode {
_currentRunLoopMode = targetMode;
_queue.queueRunMode = _currentRunLoopMode;
}
polen:
切換當(dāng)前runloop的mode,任何時(shí)間都可以切換
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消息隊(duì)列
polen:
這個(gè)LWMessageQueue是消息隊(duì)列,每個(gè)runloop里面有個(gè)消息隊(duì)列_queue和runloop mode,如下,
@implementation LWRunLoop {
LWMessageQueue* _queue;
NSString* _currentRunLoopMode;
}
從第3條( LWRunLoop.m)可以看出來, runloop執(zhí)行的時(shí)候,就是靠自己的消息隊(duì)列,將一條條消息取出來執(zhí)行掉。
不想網(wǎng)上翻頁(yè)的童鞋,我把代碼再貼一遍:
#LWRunLoop.m
- (void)run {
while (true) {
//這里面不斷循環(huán)取下一條,下一條...
LWMessage* msg = [_queue next];
@autoreleasepool {
[msg performSelectorForTarget];
[self necessaryInvocationForThisLoop:msg];
}
}
}
7.2 next 消息
來看一下消息隊(duì)列獲取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:獲取下次喚醒時(shí)間
nextWakeTimeoutMillis = msg.when - now;
} else {
//polen:當(dāng)前狀態(tài)ok,可獲取到下一條消息
_isCurrentLoopBlock = NO;
_messages = msg.next;
msg.next = nil;
return msg;
}
} else {
nextWakeTimeoutMillis = -1;
}
//polen:完成了
_isCurrentLoopBlock = YES;
}
}
}
polen:
@synchronized(self) 是為了保證線程安全, 代碼的邏輯還是比較清晰的,如果message的待執(zhí)行時(shí)間還未到,就獲取下次喚醒時(shí)間nextWakeTimeoutMillis,如果已經(jīng)到了,則還是執(zhí)行,并將該runloop的_messages指向next消息(準(zhǔn)備下一輪的執(zhí)行)
其中關(guān)鍵的是這一端代碼:
while (YES) {
[_nativeRunLoop nativeRunLoopFor:nextWakeTimeoutMillis];
...
}
//polen:點(diǎn)進(jìn)去詳情是這樣的
- (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 下面會(huì)解釋
// must read mReadWakeFd, or result in readwake always wake
[self nativePollRunLoop];
} else {
NSLog(@"other event happend.");
}
}
}
}
polen:
這個(gè)其實(shí)就是讀取事件列表的事情了,里面有幾個(gè)重要的點(diǎn):
7.2.1 kevent函數(shù)
int ret = kevent(_kq, NULL, 0, events, MAX_EVENT_COUNT, waitTime);
說明下:第一個(gè)參數(shù)_kq是LWNativeLoop結(jié)構(gòu)中的消息隊(duì)列
//基本的類型結(jié)構(gòu)
@implementation LWNativeLoop {
int _mReadPipeFd; //polen:pip 管道的讀端
int _mWritePipeFd;//polen:pip 管道的寫端
int _kq; //polen:對(duì),就是這個(gè)
NSMutableArray* _fds;
}
// 初始化函數(shù)里面有:
_kq = kqueue();
NSAssert(_kq != -1, @"Failure in kqueue(). errno=%d", errno);
polen:
利用Linux系統(tǒng)中的管道(pipe)進(jìn)程間通信機(jī)制來實(shí)現(xiàn)消息的等待和處理。通過kevent函數(shù)可以知道剩余消息事件的個(gè)數(shù)值ret,從而遍歷這些消息. runloop的等待就是通過這個(gè)函數(shù)實(shí)現(xiàn)的,如果waitTime不是null,則會(huì)等待waitime,如果為null,kevent將會(huì)阻塞,一直等待直到有事件發(fā)生為止...
|
p.s. 關(guān)于kevent的說明:
kevent函數(shù)用于和kqueue的交互。第一個(gè)參數(shù)是kqueue返回的描述符。changelist參數(shù)是一個(gè)大小為nchanges的 kevent結(jié)構(gòu)體數(shù)組。changelist參數(shù)用于注冊(cè)或修改事件,并且將在從kqueue讀出事件之前得到處理。
eventlist 參數(shù)是一個(gè)大小為nevents的kevent結(jié)構(gòu)體數(shù)組。kevent通過把事件放在eventlist參數(shù)中來向調(diào)用進(jìn)程返回事件。如果需要的 話,eventlist和changelist參數(shù)可以指向同一個(gè)數(shù)組。最后一個(gè)參數(shù)是kevent所期待的超時(shí)時(shí)間。如果超時(shí)參數(shù)被指定為 NULL,kevent將阻塞,直至有事件發(fā)生為止。如果超時(shí)參數(shù)不為NULL,則kevent將阻塞到超時(shí)為止。如果超時(shí)參數(shù)指定的是一個(gè)內(nèi)容為0的結(jié) 構(gòu)體,kevent將立即返回所有當(dāng)前尚未處理的事件。
kevent的返回值指定了放在eventlist數(shù)組中的事件的數(shù)目。如果事件 數(shù)目超過了eventlist的大小,可以通過后續(xù)的kevent調(diào)用來獲得它們。在處理事件的過程中發(fā)生的錯(cuò)誤也會(huì)在還有空間的前提下被放到 eventlist參數(shù)中。帶有錯(cuò)誤的事件會(huì)設(shè)置EV_ERROR位,系統(tǒng)錯(cuò)誤也會(huì)被放到data成員中。對(duì)于其它的所有錯(cuò)誤都將返回-1,并相應(yīng)地設(shè)置 errno。
針對(duì)這個(gè)查了下android對(duì)應(yīng)runloop的實(shí)現(xiàn)代碼:
#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/
老羅語(yǔ)錄 (羅升陽(yáng)):
首先是調(diào)用epoll_wait函數(shù)來看看epoll專用文件描述符mEpollFd所監(jiān)控的文件描述符是否有IO事件發(fā)生,它設(shè)置監(jiān)控的超時(shí)時(shí)間為timeoutMillis
當(dāng)mEpollFd所監(jiān)控的文件描述符發(fā)生了要監(jiān)控的IO事件后或者監(jiān)控時(shí)間超時(shí)后,線程就從epoll_wait返回了,否則線程就會(huì)在epoll_wait函數(shù)中進(jìn)入睡眠狀態(tài)了。返回后如果eventCount等于0,就說明是超時(shí)了.
7.2.2 EVFILT_READ
polen:
接著往后看
if (event & EVFILT_READ) {
// must read mReadWakeFd, or result in readwake always wake
[self nativePollRunLoop];
}else{
...
}
kevent結(jié)束之后,后面是事件的讀操作,里面判斷條件有一句EVFILT_READ這個(gè),EVFILT_READ是什么東西呢?
EVFILT_READ過濾器用于檢測(cè)什么時(shí)候數(shù)據(jù)可讀。kevent的ident成員應(yīng)當(dāng)被設(shè)成一個(gè)有效的描述符。盡管這個(gè)過濾器的行為和select 或這poll很像,但它返回的事件將是特定于所使用的描述符的類型的。
7.2.3 關(guān)于管道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:
這里面消息循環(huán)和處理的代碼實(shí)現(xiàn)是基于pip的,不過只有親自看源碼,才能明白其中的要以,不想看源碼,只想知道原理的,
可以直接參照我們牛逼的老羅同學(xué)(羅升陽(yáng))語(yǔ)錄:
http://blog.csdn.net/luoshengyang/article/details/6817933/
管道是Linux系統(tǒng)中的一種進(jìn)程間通信機(jī)制,具體可以參考前面一篇文章Android學(xué)習(xí)啟動(dòng)篇推薦的一本書《Linux內(nèi)核源代碼情景分析》中的第6章--傳統(tǒng)的Uinx進(jìn)程間通信。
簡(jiǎn)單來說,管道就是一個(gè)文件,在管道的兩端,分別是兩個(gè)打開文件文件描述符,這兩個(gè)打開文件描述符都是對(duì)應(yīng)同一個(gè)文件,其中一個(gè)是用來讀的,別一個(gè)是用來寫的,一般的使用方式就是,一個(gè)線程通過讀文件描述符中來讀管道的內(nèi)容,當(dāng)管道沒有內(nèi)容時(shí),這個(gè)線程就會(huì)進(jìn)入等待狀態(tài),而另外一個(gè)線程通過寫文件描述符來向管道中寫入內(nèi)容,寫入內(nèi)容的時(shí)候,如果另一端正有線程正在等待管道中的內(nèi)容,那么這個(gè)線程就會(huì)被喚醒。
這個(gè)等待和喚醒的操作是如何進(jìn)行的呢?
這就要借助Linux系統(tǒng)中的epoll機(jī)制了。
Linux系統(tǒng)中的epoll機(jī)制為處理大批量句柄而作了改進(jìn)的poll,是Linux下多路復(fù)用IO接口select/poll的增強(qiáng)版本,它能顯著減少程序在大量并發(fā)連接中只有少量活躍的情況下的系統(tǒng)CPU利用率。但是這里我們其實(shí)只需要監(jiān)控的IO接口只有mWakeReadPipeFd一個(gè),即前面我們所創(chuàng)建的管道的讀端,為什么還需要用到epoll呢?有點(diǎn)用牛刀來殺雞的味道。其實(shí)不然,這個(gè)Looper類是非常強(qiáng)大的,它除了監(jiān)控內(nèi)部所創(chuàng)建的管道接口之外,還提供了addFd接口供外界面調(diào)用,外界可以通過這個(gè)接口把自己想要監(jiān)控的IO事件一并加入到這個(gè)Looper對(duì)象中去,當(dāng)所有這些被監(jiān)控的IO接口上面有事件發(fā)生時(shí),就會(huì)喚醒相應(yīng)的線程來處理,不過這里我們只關(guān)心剛才所創(chuàng)建的管道的IO事件的發(fā)生。
Summarize
看的有點(diǎn)累,不過學(xué)了不少東西...
另,
1.想補(bǔ)充下基礎(chǔ)runloop知識(shí)的同學(xué),可以看看這里
[iOS]runloop - iOS界的EventLoop
http://www.lxweimin.com/p/033087def3a4
2.想知道這篇文章格式是怎么出來的,請(qǐng)下載插件 XSourceNote ,這個(gè)是我們的everettjf同學(xué)寫的,用起來也是很舒服??
by polen