Native looper 分析

來源:互聯網
上載者:User

    Looper是android中很重要的概念,它是android application端線程間最主要的通訊方式,同時它也是線程內部序列化處理的主要方式,Looper的核心其實是一個訊息佇列,通過不停的處理Looper訊息佇列中的訊息來完成線程間的通訊和線程內部序列化操作。任何線程想要使用訊息機制特定的操作,那麼必須線上程中建立一個Looper,java端的Looper如何使用不介紹了,所有有過android開發經驗的人都知道怎麼用,這篇文章主要介紹一下Native Looper,看它如何和JAVA層的Looper相互配合完成android中最主要的線程通訊機制的。同時寫這篇的目的是為瞭解釋文章中事件傳遞過程中,native
Looper是如何被複用實現管道通訊的。

    上面說到JAVA Looper的核心其實是一個訊息佇列,並且我們分析一下Looper.java的代碼,並沒有任何和Native有關聯的資料結構和操作,那麼唯一能和Native Looper發生聯絡的就剩下這個JAVA的訊息佇列類型MessageQueue了,也果不其然,在MessageQueue中定義了一個成員    

    private int mPtr; // used by native code

它儲存著對應的Native的訊息佇列執行個體的地址,用一個int類型的成員儲存native執行個體,這是jni開發中常用到的方式。因此MessageQueue同樣使用mPtr來表示native的訊息佇列,NativeMessageQueue@android_os_MessageQueue.cpp,看一下NativeMessageQueue的建構函式,其中定義了一個Native的Looper,

NativeMessageQueue::NativeMessageQueue() {    mLooper = Looper::getForThread();    if (mLooper == NULL) {        mLooper = new Looper(false);        Looper::setForThread(mLooper);    }}

    因此整個的結構很簡單,JAVA Looper包含一個MessageQueue,MessageQueue對應的Native 執行個體是一個NativeMessageQueue執行個體,NativeMessageQueue在建立的時候產生一個Native Looper。

    其實Native Looper存在的意義就是作為JAVA Looper機制的開關器,

    1. 當訊息佇列中有訊息存入時,喚醒Natvice Looper,至於如何發送向線程訊息,這就用到了Handler,google的文檔中說明的很詳細,不介紹了;

    2. 當訊息佇列中沒有訊息時或者訊息尚未到處理時間時,Natvice Looper block住整個線程。

    上述功能其實一句話就可以總結:建立了JAVA Looper的線程只有在有訊息待處理時才處於活躍狀態,無訊息時block在等待訊息寫入的狀態。
    下面我們就來分析Natvice Looper它是如何?這個功能的,先從Natvice Looper入手,看它能幹什麼。

   1. Native Looper初始化

    我們看一下Natvice Looper的初始化過程都作了那些工作

    1. 建立一個pipe管道mWakeReadPipeFd和mWakeWritePipeFd,這個管道的作用就是為了將block住的線程喚醒。

    2. 建立一個epoll執行個體mEpollFd,用它來監聽event觸發,event有mWakeReadPipeFd上的 wake event;還有上一篇文章當中講到的NativeInputQueue和InputDispatcher模組註冊在各自Looper中,需要監聽的的硬體裝置的事件發生時的通知event以及事件消化完的通知event。

   在建構函式中只向mEpollFd添加對mWakeReadPipeFd的監聽,NativeInputQueue和InputDispatcher模組註冊的監聽需要通過addFd()方法在各自的模組中註冊,目前來看只有NativeInputQueue真正使用到當前線程的Native Looper,而InputDispatcher是自訂了一個Native Looper,參考上一篇文章。

Looper::Looper(bool allowNonCallbacks) :        mAllowNonCallbacks(allowNonCallbacks),        mResponseIndex(0) {    int wakeFds[2];    int result = pipe(wakeFds);    LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe.  errno=%d", errno);    mWakeReadPipeFd = wakeFds[0];    mWakeWritePipeFd = wakeFds[1];    result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);    LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking.  errno=%d",            errno);    result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);    LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking.  errno=%d",            errno);#ifdef LOOPER_USES_EPOLL    // Allocate the epoll instance and register the wake pipe.    mEpollFd = epoll_create(EPOLL_SIZE_HINT);    LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance.  errno=%d", errno);    struct epoll_event eventItem;    memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union    eventItem.events = EPOLLIN;    eventItem.data.fd = mWakeReadPipeFd;    result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, & eventItem);    LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance.  errno=%d",            errno);#else    ........................................... }

 2. Native Looper的商務邏輯

    這一部分我們深入分析一下Native Looper作為JAVA Looper機制的開關控制器的。

    JAVA Looper通過調用loop()不斷的去檢測訊息佇列中是否有訊息需要處理,調用的是MessageQueue的next()方法,這個方法返回的是MessageQueue的儲存的訊息。

    loop()@Looper.java

   Message msg = queue.next(); // might block

    final Message next() {        int pendingIdleHandlerCount = -1; // -1 only during first iteration        int nextPollTimeoutMillis = 0;        for (;;) {            if (nextPollTimeoutMillis != 0) {                Binder.flushPendingCommands();            }            nativePollOnce(mPtr, nextPollTimeoutMillis);            synchronized (this) {                // Try to retrieve the next message.  Return if found.                final long now = SystemClock.uptimeMillis();                final Message msg = mMessages;                if (msg != null) {                    final long when = msg.when;                    if (now >= when) {                        mBlocked = false;                        mMessages = msg.next;                        msg.next = null;                        if (Config.LOGV) Log.v("MessageQueue", "Returning message: " + msg);                        return msg;                    } else {                        nextPollTimeoutMillis = (int) Math.min(when - now, Integer.MAX_VALUE);                    }                } else {                    nextPollTimeoutMillis = -1;                }                // If first time, then get the number of idlers to run.                if (pendingIdleHandlerCount < 0) {                    pendingIdleHandlerCount = mIdleHandlers.size();                }                if (pendingIdleHandlerCount == 0) {                    // No idle handlers to run.  Loop and wait some more.                    mBlocked = true;                    continue;                }                if (mPendingIdleHandlers == null) {                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];                }                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);            }            // Run the idle handlers.            // We only ever reach this code block during the first iteration.            for (int i = 0; i < pendingIdleHandlerCount; i++) {                final IdleHandler idler = mPendingIdleHandlers[i];                mPendingIdleHandlers[i] = null; // release the reference to the handler                boolean keep = false;                try {                    keep = idler.queueIdle();                } catch (Throwable t) {                    Log.wtf("MessageQueue", "IdleHandler threw exception", t);                }                if (!keep) {                    synchronized (this) {                        mIdleHandlers.remove(idler);                    }                }            }            // Reset the idle handler count to 0 so we do not run them again.            pendingIdleHandlerCount = 0;            // While calling an idle handler, a new message could have been delivered            // so go back and look again for a pending message without waiting.            nextPollTimeoutMillis = 0;        }    }

    在擷取MessageQueue中訊息過程中,我們發現next()是一個迴圈,除了擷取訊息佇列之外,最重要的一點就是去監聽Natvie Looper的event觸發,調用nativePollOnce(mPtr, nextPollTimeoutMillis); 它最終會調用到pollInner()@Looper.cpp。我們來看看pollInner都幹了些什嗎?

    1. 等待mEpollFd的事件觸發,我們前面說過,這個事件觸發有兩種,第一個就是喚醒Native Looper的wake訊息,另外一個就是複用Native Looper的其他訊息,如NativeInputQueue和InputDispatcher的管道檢測(目前android也就這兩個模組使用到了)。

當epoll_wait()的等待時間不為0時,即JAVA Looper傳遞下來的nextPollTimeoutMillis值,那麼整個線程就被block在這兒了。

    pollInner()@Looper.cpp

    struct epoll_event eventItems[EPOLL_MAX_EVENTS];    int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);    bool acquiredLock = false;

   2. 如果有事件觸發發生,wake或者其他複用Looper的event,處理event,這樣整個Native Looper就從block狀態中解脫出來了,整個線程也就解脫出來了,JAVA Looper則會執行nativePollOnce(mPtr, nextPollTimeoutMillis);下面的語句,next()@MessageQueue.java後面的語句就不解釋了。

    我們只需要注意nextPollTimeoutMillis值的設定,如果訊息尚未到達處理時間,則nextPollTimeoutMillis值則為距離該訊息處理時間的總時間長度,表明Native Looper只需要block到訊息需要處理的時間就行了。如果沒有訊息待處理,那麼將一直Native Looper將一直block住,等待wake event。

    那麼什麼時候會有wake event發生呢?只有在有新的訊息被儲存到MessageQueue時,會向Native Looper發起wake event。

    enqueueMessage()@MessageQueue.java

        if (needWake) {            nativeWake(mPtr);        }

     整個Native Looper的基本機制就是這樣的,保證線上程無訊息可處理時,能夠儘可能的減少CPU的利用,將寶貴的CPU資源交給其他線程或者進程處理,這一點在行動裝置中是很重要的。

 3. Native Looper擴充應用    Native Looper儘管通常情況下是和JAVA 層的Looper和MessageQueue配合使用的,作為JAVA Looper的開關控制器存在的,但是鑒於上面我們對Native Looper的分析,我們發現在native code開發時,我們完全也可以單獨使用Native Looper,比如說在開發的native code中如果使用到了pipe或者socket通訊的話,Native Looper將會是把利器,我們通過它能夠很好的管理pipe或者socket等的通訊。正如InputDispatcher所做的一樣。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.