相关类
Threads.cpp
threads.h
Thread.h
在C++层的输入处理类中碰到一个线程相关的问题
1:InputReaderThread读取线程及InputDispatcherThread派发线程是如何去执行threadLoop方法的?
2:事件读取及派发线程肯定是一个循环线程,因为它要持续的接收并派发驱动层的触摸事件,threadLoop如何循环?
在Native层实现一个Thread类的派生类,Thread中有一个虚方法,派生类需实现
virtual bool threadLoop()
在实现该方法时,注意以下规则
当返回true时,如果requestExit没有被调用,则threadLoop会再次调用
当返回false时,线程退出
Thread的run方法主要功能是在C层创建线程
if (mCanCallJava) {
res = createThreadEtc(_threadLoop, this, name, priority, stack, &mThread);
} else {
res = androidCreateRawThreadEtc(_threadLoop, this, name, priority, stack, &mThread);
}
当mCanCallJava是true时,createThreadEtc定义在AndroidThreads.h中的内联函数,调用androidCreateThreadEtc
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。
_threadLoop控制threadLooper的循环
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方法
网友评论