Threads.cpp
int Thread::_threadLoop(void* user) { Thread* const self = static_cast<Thread*>(user); sp<Thread> strong(self->mHoldSelf); wp<Thread> weak(strong); self->mHoldSelf.clear(); bool first = true; do { bool result; if (first) { first = false; self->mStatus = self->readyToRun(); result = (self->mStatus == NO_ERROR); if (result && !self->exitPending()) { // Binder threads (and maybe others) rely on threadLoop // running at least once after a successful ::readyToRun() // (unless, of course, the thread has already been asked to exit // at that point). // This is because threads are essentially used like this: // (new ThreadSubclass())->run(); // The caller therefore does not retain a strong reference to // the thread and the thread would simply disappear after the // successful ::readyToRun() call instead of entering the // threadLoop at least once. result = self->threadLoop(); //threadLoop()是用户自己继承Thread时需要实现的 } } else { result = self->threadLoop(); } // establish a scope for mLock { Mutex::Autolock _l(self->mLock); if (result == false || self->mExitPending) { self->mExitPending = true; self->mRunning = false; // clear thread ID so that requestExitAndWait() does not exit if // called by a new thread using the same thread ID as this one. self->mThread = thread_id_t(-1); // note that interested observers blocked in requestExitAndWait are // awoken by broadcast, but blocked on mLock until break exits scope self->mThreadExitedCondition.broadcast(); break; } } // Release our strong reference, to let a chance to the thread // to die a peaceful death. strong.clear(); // And immediately, re-acquire a strong reference for the next loop strong = weak.promote(); } while(strong != 0); return 0; }
//在工作线程退出前唤醒这个线程做扫尾工作 status_t Thread::requestExitAndWait() { Mutex::Autolock _l(mLock); if (mThread == getThreadId()) { ALOGW( "Thread (this=%p): don't call waitForExit() from this " "Thread object's thread. It's a guaranteed deadlock!", this); return WOULD_BLOCK; } mExitPending = true;
/*
条件变量的等待,这里为什么要通过while循环来反复检测mRunning?
因为某些时候即使条件类没有被触发,wait也会返回。关于这个问题,强烈建议读者阅读
前面推荐的《Programming with POSIX Thread》一书。
*/ while (mRunning == true) { mThreadExitedCondition.wait(mLock); } // This next line is probably not needed any more, but is being left for // historical reference. Note that each interested party will clear flag. mExitPending = false; return mStatus; }
也就是说thread的实现是2个线程在工作

浙公网安备 33010602011771号