相关类
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方法事件