相關類
Threads.cpp
threads.h
Thread.handroid
在C++層的輸入處理類中碰到一個線程相關的問題
1:InputReaderThread讀取線程及InputDispatcherThread派發線程是如何去執行threadLoop方法的?
2:事件讀取及派發線程確定是一個循環線程,由於它要持續的接收並派發驅動層的觸摸事件,threadLoop如何循環?函數
在Native層實現一個Thread類的派生類,Thread中有一個虛方法,派生類需實現oop
virtual bool threadLoop()
在實現該方法時,注意如下規則
當返回true時,若是requestExit沒有被調用,則threadLoop會再次調用
當返回false時,線程退出this
if (mCanCallJava) { res = createThreadEtc(_threadLoop, this, name, priority, stack, &mThread); } else { res = androidCreateRawThreadEtc(_threadLoop, this, name, priority, stack, &mThread); }
當mCanCallJava是true時,createThreadEtc定義在AndroidThreads.h中的內聯函數,調用androidCreateThreadEtcspa
int androidCreateThreadEtc(android_thread_func_t entryFunction, void *userData, const char* threadName, int32_t threadPriority, size_t threadStackSize, android_thread_id_t *threadId) { return gCreateThreadFn(entryFunction, userData, threadName,threadPriority, threadStackSize, threadId); }
gCreateThreadFn默認時等於androidCreateRawThreadEtc
當mCanCallJava是false時,調用androidCreateRawThreadEtc,建立線程線程
int result = pthread_create(&thread, &attr,(android_pthread_entry)entryFunction, userData);
pthread_create是Linux建立線程的方法,並執行entryFunction,對應的是_threadLoop
綜上,在Thread類的run方法執行後,會調用底層庫libpthread的方法pthread_create建立線程,並執行回調方法_threadLoop。code
do { bool result; if (first) { first = false; self->mStatus = self->readyToRun(); result = (self->mStatus == NO_ERROR); if (result && !self->exitPending()) { result = self->threadLoop(); } } else { result = self->threadLoop(); } { Mutex::Autolock _l(self->mLock); if (result == false || self->mExitPending) {//當result 爲false或者result 爲true且mExitPending時,退出循環,退出線程 self->mExitPending = true; self->mRunning = false; self->mThread = thread_id_t(-1); self->mThreadExitedCondition.broadcast(); break; } } strong.clear(); strong = weak.promote(); } while(strong != 0);
threadLooper派生類返回true,可實現線程循環執行threadLooper方法事件